Radio Button Control in ASP.net Datalist/Repeater

Friday, February 1, 2008

The other day I had to build a simple listing of data that required having a radio button on each line so as to enable a user to select and option. I planned to use a datalist control and to place a radio button control in the itemtemplate.

When I ran a quick test I immediately noticed a peculiar issue, all the radio buttons where selectable at the same time!

As usual, I googled the symptom and quickly found that there seems to be an issue with both ASP.net 1.1 and 2.0 where the radio button controls in the list become all selectable (more like checkboxes) while the whole idea behind a radio button is to have just one in the list selectable at a time.

After further reseach, I found that the reason why this is happening is simply because of the way the asp.net assigns the Control's ID at run-time.  Basically this problem occurs because the Repeater/Datalist server control implements the INamingContainer interface, which requires that all controls that are nested within it must have a unique name when rendered in Hypertext Markup Language (HTML). Therefore, the HTML name attribute of any rendered child server control is unique. In order to work correctly, radio buttons must have the same ID.

Thankfully, I was able to find some resources online that helped me quickly overcome this limitation (bug?). Here is what you need to do:

In your ASPX or ASCX add the following piece of Javascript:

<script language="javascript" type="text/javascript">
 function SetUniqueRadioButton(nameregex, current)
{
   re = new RegExp(nameregex);
   for(i = 0; i < document.forms[0].elements.length; i++)
   {
      elm = document.forms[0].elements[i]
      if (elm.type == 'radio')
      {
         if (re.test(elm.name))
         {
            elm.checked = false;
         }
      }
   }
   current.checked = true;
}
</script>

Now, in your code behind, and in the ItemDataBound event of your Repeater/Datalist find the Radio Button control and add an OnClick attribute to call the Javascript function you just added to your page:

Dim strFunction As String = "SetUniqueRadioButton('YourDalistID.*YourRadioButtonControlGroupName',this)"
RadioButtonControl1.Attributes.Add("onclick", strFunction)

Make sure that you replace the YourDatalistID and YourRadioButtonControlGroupName tokens above with your naming scheme.

In short, the javascript will loop through the radio buttons in your repeater/datalist and uncheck any of the previously checked radion buttons.

Comments are closed