简体   繁体   中英

Get selected radio button not in a list in ASP .NET

I have a number of radio buttons belonging to a group. I don't have them in a list, as they are all scattered around the page. How can I easily get the selected radio button?

Maybe not the fastest way, but something like this should work:

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;
}

Use the "GroupName" attribute to group radio buttons into a group. This will keep them behaving as a group. You will still need to query them individually for checked status.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM