如何计算VS C#2010中属于同一组的单选按钮数量?

时间:2013-11-01 05:15:49

标签: c# asp.net

我希望许多单选按钮位于同一组中。有人可以帮帮我吗?

3 个答案:

答案 0 :(得分:0)

使用asp:RadioButtonList

<asp:RadioButtonList ID="rblMyList" runat="server">
    <asp:ListItem Text="Male" Value="Male"></asp:ListItem>
    <asp:ListItem Text="Female" Value="Female"></asp:ListItem>
</asp:RadioButtonList>

答案 1 :(得分:0)

尝试此操作以获取具有相同组名的Radiobutton

C#:

 int count = 0;
        foreach (RadioButton rb in divContainer.Controls.OfType<System.Web.UI.WebControls.RadioButton>())
        {
            if(rb.GroupName=="a")
            {
                count++;
            }
        }

注意:asp:RadioButtonList也是一个更好的选择

答案 2 :(得分:0)

试试这个:(基于Renju vinod回答this

    public IEnumerable<Control> GetAll(Control control, Type type)
    {
        var controls = control.Controls.Cast<Control>();
        return controls.SelectMany(ctrls => GetAll(ctrls, type)).Concat(controls).Where(c => c.GetType() == type);
    }

现在你可以像下面这样得到

        string GroupName = "MyGroupName"; // Your known group name
        int numberOfRadioOfThisGroup = 0;
        var cntls = GetAll(this, typeof(RadioButton));
        foreach (Control cntrl in cntls)
        {
            RadioButton rb = (RadioButton)cntrl;
            if (rb.GroupName == GroupName)
            {
                numberOfRadioOfThisGroup++;
            }
        }

        // numberOfRadioOfThisGroup will now have the count of number of radiobuttons belonging to your group