Friday, October 7, 2011

Working with a dynamic RadioButtonList

ASP.NET provides a RadioButtonList control, which has the useful ability to bind text and values (perhaps, for example, retrieved from a database) to a set of radio buttons at runtime. You might find the need to examine and manipulate attributes of the radio buttons in the list, even though you don't know in advance what those radio buttons may be. Here's an example of how to do that.

In my example, there's a list of radio buttons. The list may (or may not) include a radio button labeled "Countdown". If the list includes a "Countdown" radio button, then I want to disable it. Furthermore, if "Countdown" was selected, I want to instead select the first radio button in the list. Here's the code:

foreach (ListItem listItem in rblSelectionType.Items)
{
if (listItem.Text == "Countdown")
{
if (listItem.Selected)
rblSelectionType.SelectedIndex = 0;
listItem.Enabled = false;
break;
}
}

Thanks to this tutorial for setting me on the right track.