July 16 2008

Fix for bug Q316495 / 316495 : Radio Buttons Are Not Mutually Exclusive

Update: This “fix” unfortunately breaks postback logic.  No matter what I seem to do, the radio buttons are unchecked on a postback.  It must be a mismatch with the viewstate and what is in the Html.  Any suggestions?

I thought I was going mad, but the ASP.Net RadioButton control completely ignores whatever you put in the property GroupName. Instead the INamingContainer control makes all the control’s name unique, which is not useful if you’re using a repeater or, in my case, radio buttons in two different containers.

There is a javascript fix to this bug, but I don’t find this satisfactory as not all browsers support javascript, and then your functionality would be broken.

My fix overrides the Render method to clean up this buggy name mess.

Libraries used:

using System.IO;
using System.Text.RegularExpressions;

Define a regular expression to find the incorrect name tag and no others (change to match your radio buttons

    // finds the any radio buttons of a certain naming convention
    private static Regex _bugFix = 
        new Regex(@"name=""[^""]+\$offer_[^""]+""", 
        RegexOptions.Compiled);

Then override the Render method and set them all to the same name (in this case “offer”)

    protected override void Render(HtmlTextWriter output)
    {
        // Get the rendered page
        StringWriter writer = new StringWriter();
        HtmlTextWriter buffer = new HtmlTextWriter(writer);
        base.Render(buffer);
        string htmlMarkup = writer.ToString();
       
       //replace the name="" tag from the control
        htmlMarkup = _bugFix.Replace(htmlMarkup, "name='offer'");

        //write html
        output.Write(htmlMarkup);
    }
Comments (View)
blog comments powered by Disqus

Please...

Leave a comment if this has helped or offended you.

StackOverflow Id