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?
A:
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.
Cylon Cat
2010-09-06 21:47:19
Yes, they are in a group. I am hoping to find something like GetSelectedRadioButton(groupName)
naveed
2010-09-06 21:51:57
I'm not aware of anything like that. The next best alternative would be to have all the checkboxes in a group raise the same checkchanged event. In the event handler, all you have to do is check the name of the control that raised the event.
Cylon Cat
2010-09-07 00:27:35
+2
A:
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;
}
Tom Vervoort
2010-09-06 22:27:50