ASP.Net c# 如何确定一个指定 GroupName 中哪个单选按钮被选中?

11

我有30个单独的RadioButton(单选按钮)。我不能使用一个RadioButtonList(单选按钮列表)。这些按钮分为3组,每组都有唯一的GroupName属性。在Web浏览器中一切正常运行。如何在post back时确定每个给定的GroupName属性下哪个按钮被选择?

编辑:我使用的函数

private string getRadioValue(ControlCollection clts, string groupName)
{
    string ret = "";
    foreach (Control ctl in clts)
    {
        if (ctl.Controls.Count != 0)
        {
            if (ret == "")
                ret = getRadioValue(ctl.Controls, groupName);
        }

        if (ctl.ToString() == "System.Web.UI.WebControls.RadioButton")
        {
            RadioButton rb = (RadioButton)ctl;
            if (rb.GroupName == groupName && rb.Checked == true)
                ret = rb.Attributes["Value"];
        }
    }
    return ret;
}
3个回答

9

您需要检查所有单选按钮的已选属性。
没有简单的方法可以通过组名来检查它。(您可以编写扫描某个控件容器中的所有单选按钮并返回组名、控件已选状态的列表的方法,但更容易的方法是扫描所有单选按钮)


1

将相同的处理程序附加到每个单选按钮。然后检查您要查找的属性。将“启用回发”设置为true。

protected void RadioButton1_30_CheckedChanged(object sender, EventArgs e)
{
    RadioButton rb = (RadioButton)sender;        
    string txtVal = rb.Text;
    string groupName= rb.GroupName;
    int tmpInt;
    Int32.TryParse(txtVal, out tmpInt);

}

5
每次用户更改单选框时,这将需要刷新页面。 - Justin808

0

您可以使用 Request.Form("groupName")。


1
这不起作用,因为ASP.NET会向name属性添加crud。例如:ctl00$cphBody$Mthree。 GroupName是Mthree,如果我要使用Request.Form,我需要知道crud部分,因为仅使用GroupName是无法访问的。 - Justin808
如果您的页面设置需要混淆,通常可以使用控件的ClientID属性找出crud部分。 - joelt
CRUD部分对于ID和名称是相同的吗?我没有看到客户端名称参数。 - Justin808
要么完全相同,要么存在一些小差异——比如一个使用 $ 而另一个使用 _ 或 :,因此通常可以使用字符串替换来解决问题。 - joelt

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接