SOF User SOF User - 1 year ago 94
ASP.NET (C#) Question

Radio option GroupName problem in Dynamic loading user Control

I have User Control

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

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;

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 Source

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.

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.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]

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download