后台获取不规则排列RadioButton组的值

获取多个RadioButton的值,我们一般会使用服务器控件RadioButtonList:

<asp:RadioButtonList ID="rbl" runat="server">
    <asp:ListItem Value="1">单选1</asp:ListItem>
    <asp:ListItem Value="2">单选2</asp:ListItem>
    <asp:ListItem Value="3">单选3</asp:ListItem>
</asp:RadioButtonList>

后台通过 this.rbl.SelectedValue 来获取选则的值,关于RadioButtonList的使用,这里就不介绍了。

由于RadioButtonList的排列是有规则的,不管是横排还是竖排,紧凑还是对齐。

那么,如果是一组没有规则的RadioButton,那么这些值怎么获取呢?

<asp:RadioButton ID="rb1" runat="server" GroupName="new" Text="单选1" />
<div>……</div>
<asp:RadioButton ID="rb2" runat="server" GroupName="new" Text="单选2" />
<div>……</div>
<asp:RadioButton ID="rb3" runat="server" GroupName="new" Text="单选3" />
<div>……</div>

办法当然有很多,比如最常用的:当选中值的时候,用JS将值放入页面的隐藏控件中,再在后台获取隐藏控件的值。

这里介绍另外一种方法,比如页面禁用JS的时候,这种方法就有效了:

首先,在涵盖所有需要取值的RadioButton外面,加一个div,并且runat="server"

<div id="div1" runat="server">
    <asp:RadioButton ID="rb1" runat="server" GroupName="new" Text="单选1" />
    <div>……</div>
    <asp:RadioButton ID="rb2" runat="server" GroupName="new" Text="单选2" />
    <div>……</div>
    <asp:RadioButton ID="rb3" runat="server" GroupName="new" Text="单选3" />
</div>
<div>……</div>

然后,后台写一个这样的方法:

public string GetRadioButtonGroupValue(Control ctrl, string controlName)
{
   foreach (Control control in ctrl.Controls)
   {
      if (control is RadioButton)
      {
         RadioButton lControl = control as RadioButton;
         if (lControl.Checked && lControl.GroupName == controlName)
         {
            return lControl.Text;
         }
      }
   }
    return null;
}

最后,调用就可以了:

GetRadioButtonGroupValue(this.div1, "new")
原文地址:https://www.cnblogs.com/kandyvip/p/3173632.html