SOF User SOF User - 3 months ago 19
ASP.NET (C#) Question

Radio option GroupName problem in Dynamic loading user Control ASP.net

I have User Control

<table style="border-width: 0">
<tr>
<td style="vertical-align: middle;">
<asp:RadioButton ID="rdOption" runat="server" Text="I m testing"
GroupName="Questions" oncheckedchanged="rdOption_CheckedChanged"
AutoPostBack="True"/>
</td>
<td style="vertical-align: middle; padding-left: 10px">
<asp:TextBox ID="txtOthers" runat="server" CssClass="txtbox" Visible="false"></asp:TextBox>
</td>
</tr>
</table>

protected void Page_Load(object sender, EventArgs e)
{
rdOption.GroupName = "myGroup";
rdOption.Text = Option.OptionDesc;
}


on Survery.aspx I loaded that user control dynamically

foreach (clsOptions option in _CurrentQuestion.Options)
{
UserControls_OptionField ctrl = Page.LoadControl("~/UserControls/OptionField.ascx") as UserControls_OptionField;
ctrl.Option = option;
pnlOption.Controls.Add(ctrl);
}


Problem is that each option have diffrent group name shown below. Thats why options are not working properly and all option can be selected while in MCQs only one option can be selected.

<input id="ContentPlaceHolder1_ctl01_rdOption" type="radio" name="ctl00$ContentPlaceHolder1$ctl01$myGroup" value="rdOption">

<input id="ContentPlaceHolder1_ctl02_rdOption" type="radio" name="ctl00$ContentPlaceHolder1$ctl02$myGroup" value="rdOption">


enter image description here

Answer

I think that this is a bug that is in ASP.Net since 1.0(awesome, they have forgotten that completely ^^).

You could try following solution that works for a Repeater(or any databound control) but should also work for your dynamic UserControls.

The problem is that ASP.Net renders different unique names for different NamingContainers and therefore the RadioButtons get different GroupNames.

http://weblogs.asp.net/joseguay/archive/2008/07/24/having-radiobuttons-on-a-repeater-or-datalist.aspx

Put this in your HEAD section of your page's:

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

Add the clientside onclick event to the RadioButtons with appropriate parameters:

string script = "SetUniqueRadioButton('rdOption.*myGroup',this)";
rdOption.Attributes.Add("onclick", script);

[not tested]

Comments