获取选定的单选按钮不在ASP .NET的列表中

nav*_*eed 5 c# asp.net radio-button

我有一些属于一个组的单选按钮.我没有将它们放在列表中,因为它们都散落在页面周围.如何轻松获取所选单选按钮?

Tom*_*ort 9

也许不是最快的方式,但这样的事情应该有效:

private RadioButton GetSelectedRadioButton(string groupName)
{
    return GetSelectedRadioButton(Controls, groupName);
}

private RadioButton GetSelectedRadioButton(ControlCollection controls, string groupName)
{
    RadioButton retval = null;

    if (controls != null)
    {
        foreach (Control control in controls)
        {
            if (control is RadioButton)
            {
                RadioButton radioButton = (RadioButton) control;

                if (radioButton.GroupName == groupName && radioButton.Checked)
                {
                    retval = radioButton;
                    break;
                }
            }

            if (retval == null)
            {
                retval = GetSelectedRadioButton(control.Controls, groupName);
            }
        }
    }

    return retval;
}
Run Code Online (Sandbox Code Playgroud)