ASP.NET Tip: Using RadioButton Controls in a Repeater

The ASP.NET Repeater control is one of my favorites, mainly because it is fully customizable and it allows me to build many types of applications. However, it does have a few downsides in terms of which controls it can host. If you try to add a RadioButton control into a Repeater's ItemTemplate or AlternatingItemTemplate, you end up with a situation where all your RadioButtons can be checked. This obviously isn't a good thing.

In case you haven't used them in ASP.NET, RadioButton controls each have a unique ID but a common GroupName parameter. This allows the RadioButton controls to work together as a group. However, a Repeater mangles the control IDs and group names, causing them to not work correctly. The fix is a simple bit of JavaScript that you can add to pages with Repeaters and RadioButton controls. This function was originally provided in a newsgroup by Microsoft support and appears to be a reliable fix.

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.name))
         {
            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)
      return;

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

}

The end result of this code is properly functioning RadioButton controls with minimum hassle. This code works equally well in ASP.NET 1.1 and 2.0 Because Microsoft didn't change the feature/bug/whatever that causes this behavior. The Repeater is working as designed and is a known issue.

About the Author

Eric Smith is the owner of Northstar Computer Systems, a Web-hosting company based in Indianapolis, Indiana. He is also a MCT and MCSD who has been developing with .NET since 2001. In addition, he has written or contributed to 12 books covering .NET, ASP, and Visual Basic.



Comments

  • Another way

    Posted by Dennis V McEnaney on 02/10/2016 10:14am

    Another way? A custom control/override to work-around the 'HtmlInputControl.RenderAttributes()' method by ignoring the 'RenderedNameAttribute' property: /// /// HACK: For Microsoft&aposs bug whereby they mash-up value of the "name" attribute. /// public class NameFixHtmlInputRadioButton : HtmlInputRadioButton { protected override void RenderAttributes(HtmlTextWriter writer) { // BUG: Usage of 'HtmlInputControl.RenderedNameAttribute' // writer.WriteAttribute("name", this.RenderedNameAttribute); writer.WriteAttribute(@"name", Attributes[@"Name"]); Attributes.Remove(@"name"); var flag = false; var type = Type; if (! string.IsNullOrEmpty(type)) { writer.WriteAttribute(@"type", type); Attributes.Remove(@"type"); flag = true; } base.RenderAttributes(writer); if (flag && DesignMode) { Attributes.Add(@"type", type); } writer.Write(@" /"); } }

    Reply
  • How would you validate this?

    Posted by awoomer on 03/15/2010 03:55pm

    This works great and I realize it's an old post but I'm stuck on how to validate whether a selection was made or not. Any ideas? I'd even settle for checking one by default to start out with. My javascript is a little shaky. Also, my repeater is in the first active step of a wizard control. Thanks

    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • As all sorts of data becomes available for storage, analysis and retrieval - so called 'Big Data' - there are potentially huge benefits, but equally huge challenges...
  • The agile organization needs knowledge to act on, quickly and effectively. Though many organizations are clamouring for "Big Data", not nearly as many know what to do with it...
  • Cloud-based integration solutions can be confusing. Adding to the confusion are the multiple ways IT departments can deliver such integration...

Most Popular Programming Stories

More for Developers

RSS Feeds

Thanks for your registration, follow us on our social networks to keep up-to-date