ASP.NET RadioButton messing with the name (groupname)


I got a templated control (a repeater) listing some text and other markup. Each item has a radiobutton associated with it, making it possible for the user to select ONE of the items created by the repeater.

The repeater writes the radiobutton setting its id and name generated with the default ASP.NET naming convention making each radiobutton a full 'group'. This means all radiobuttons are independent on each other, which again unfortunately means I can select all radiobuttons at the same time. The radiobutton has the clever attribute 'groupname' used to set a common name, so they get grouped together and thus should be dependant (so I can only select one at a time). The problem is – this doesn't work – the repeater makes sure the id and thus the name (which controls the grouping) are different.

Since I use a repeater (could have been a listview or any other templated databound control) I can't use the RadioButtonList. So where does that leave me?

I know I've had this problem before and solved it. I know almost every ASP.NET programmer must have had it too, so why can't I google and find a solid solution to the problem? I came across solutions to enforce the grouping by JavaScript (ugly!) or even to handle the radiobuttons as non-server controls, forcing me to do a Request.Form[name] to read the status. I also tried experimenting with overriding the name attribute on the PreRender event – unfortunately the owning page and masterpage again overrides this name to reflect the full id/name, so I end up with the same wrong result.

If you have no better solution than what I posted, you are still very welcome to post your thoughts – at least I'll know that my friend 'jack' is right about how messed up ASP.NET is sometimes 😉

Best Solution

ASP.NET Tip: Using RadioButton Controls in a Repeater

This is the code for the JavaScript function:

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.checked = false;
   current.checked = true;

The code is linked to the Repeater through the ItemDataBound event. For it to work properly, you need to know the name of the Repeater control, as well as the GroupName you're assigning to the RadioButtons. In this case, I'm using rptPortfolios as the name of the Repeater, and Portfolios as the group name:

protected void rptPortfolios_ItemDataBound(object sender,
                                           RepeaterItemEventArgs e)
   if (e.Item.ItemType != ListItemType.Item && e.Item.ItemType
      != ListItemType.AlternatingItem)

   RadioButton rdo = (RadioButton)e.Item.FindControl("rdoSelected");
   string script =
   rdo.Attributes.Add("onclick", script);



Related Question