Thursday, 25 March 2010

ASP.Net (VB) fix for RadioButton's using GroupName in a Repeater

I've just had the experience of learning that due to the way a repeater renders, in terms of giving names to the controls within, the GroupName attribute doesn't actually work.

This is the official Microsoft bug: http://support.microsoft.com/kb/316495/en-us

I can understand why it fails but it's a little frustrating that the only solution I could find was a javascript one.I originally found it on this website but I wanted to write the script in my code behind and in VB rather than C#.

Here is the code I converted it to.

To start off with in the Page Load event I had

Dim objSB As New StringBuilder

objSB.Append("" & Environment.NewLine)
ClientScript.RegisterClientScriptBlock(Me.GetType(), "UniqueRadio", objSB.ToString)

This just inserts the required javascript at the top of the page (and it should validate OK).

Then within the ItemDataBound event, amongst all the other code in there I put

If e.Item.ItemType = ListItemType.Item OrElse e.Item.ItemType = ListItemType.AlternatingItem Then
Dim rb As RadioButton = DirectCast(e.Item.FindControl("RADIOBUTTONID"), RadioButton)
rb.Attributes.Add("onclick", "setUniqueRadioButton('rptList.*GROUPNAME',this)")
End If

The text in capitals are what needs replacing. The RADIOBUTTONID should be the ID of the radio button and the GROUPNAME should be changed to the group name being used.

If you had multiple 'groups' on the same page you should only need to use the second piece of code twice. The javascript at the top can be referenced throughout the page.

No comments:

Post a Comment