Using and grouping RadioButton Controls in a Repeater

By default, you cannot group radiobutton controls within a repeater as the repeater mangles the names. I had this exact problem when changing from checkboxes to radio buttons – after searching Google for 10 mins, I found a post at the following site by Eric Smith which i’ll copy the relevant info here so I don’t lose it

http://www.codeguru.com/csharp/csharp/cs_controls/custom/article.php/c12371/

Add the following Javascript code to your page:

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;
}

Now for the repeater itself,

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)
      return;

   RadioButton rdo = (RadioButton)e.Item.FindControl("rdoSelected");
   string script =
      "SetUniqueRadioButton('rptPortfolios.*Portfolios',this)";
   rdo.Attributes.Add("onclick", script);

}

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.