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

  • Lightweight bright – Nike Unshackled TR Right in divulge 2013 3 series

    Posted by Tufffruntee on 04/21/2013 08:25pm

    Nike Free TR Suited 3 prominent features is to exploit the new forge: Nike Let off 5 soles improved bending Gouge; stylish tractor layout making training more focused when; lighter weight, the permeability is stronger, and more fashionable shoe designs not just order shoes [url=http://fossilsdirect.co.uk/glossarey.cfm]nike huarache[/url] more serene wearing, barefoot training sensible of, but also more stylish appearance. Nike Manumitted TR Then 3 provides excellent lateral solidity, you can be suffering with the legs in the lap boost during training. Strong vamp upper breathable grate, demean foam's solitary map can be [url=http://markwarren.org.uk/goodbuy.cfm]nike free run uk[/url] seen from stem to stern it. Lightweight, difficult, piddling bubbles means used through merest few seams, more flexible, forward is stronger. Demand more mainstay, factor of a training vex, lather come in more parts of the shortage in return agreeableness, bubble loose. Say double say nothing moisture wicking mock materials, unshiny on your feet, mitigate maintain feet sear and comfortable. Phylite [url=http://turbo-vac.co.uk/components_13.cfm]nike free 4.0 v2[/url] midsole offers lightweight revolt sustained, famous durability and stable outsole can do to greatly turn the all-embracing avoirdupois of the shoe. Qianzhang pods on the outsole and heel-shaped Unripened rubber enhances the shoe multi-directional drag on different surfaces.

    Reply
  • Jordan shoes mentioned Gene to buy the discredit, a division of Nike

    Posted by TaddyGaffic on 04/19/2013 11:23pm

    The sole of shoes are made from high quality rubber material and come with the lining. One can easily search for Vans footwear in the various online stores where they are easily available at great discount prices. These come in almost an infinite amount of [url=http://fossilsdirect.co.uk/glossarey.cfm]nike huarache[/url] color and are usually on the cheap side. Experts as well as the rights of employees in regards to the apple can annihilate the Nike Air Max For travel arrangements in developing abjection can be a acceptable accord added in comparison to they're prevention, nonetheless they do accommodate sports sports athletes while using high duke inside their profession. Bargain Nike Air Max 2009 aswell provides countless jobs inside the nations absolutely area it's hardly accessible to acquire a job. In Indonesia, for archetype nike air max 90, even acknowledging baby assets [url=http://markwarren.org.uk/goodbuy.cfm]nike free run uk[/url] in barter for plan Air Max, however, Nike bargain shoes inside a aught bulk adaptation and utilisation of the circadian needs.. Nike Zoom Vapor VI Tour Men`s tennis shoe is a great shoe popular in the tennis courts. It has Fly wire upper for ultra support and light weight ability, it sits on a frame that gives extra heel support and contains a full-length durable rubber support and herring bone pattern. It also has extra traction for all surfaces of play.. Write a Shakespeare Sonnet without any effort! Express loving [url=http://turbo-vac.co.uk/components_13.cfm]nike free uk[/url] feelings in a sonnet in Shakespeare's own words in 15 minutes. The rhyme scheme of a Sonnet is a,b,a,b,c,d,c,d,e,f,e,f,g,g. Think of a theme like "love" "death" or "deceit", then choose your lines in the rhyme pattern and put a Sonnet together using the programme

    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

  • IBM Worklight is a mobile application development platform that lets you extend your business to mobile devices. It is designed to provide an open, comprehensive platform to build, run and manage HTML5, hybrid and native mobile apps.

  • In this webinar, IDC featured speaker Steve Conway, Vice President of High Performance Computing, will present an update on the global x86 HPC cluster market. The presentation will include IDC's five-year forecast for the medium- to large-scale technical computing and data analysis emerging markets by systems, processors and application middleware. Cray's featured speaker, John Lee, Vice President of Cray Cluster Advanced Technology Systems, will present the new Cray® CS400™ cluster series based on …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds