Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 747
naveed Avatar asked Sep 06 '10 21:09

naveed


1 Answers

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;
}
like image 132
Tom Vervoort Avatar answered Nov 15 '22 05:11

Tom Vervoort