【问题标题】:Check if all radio buttons are selected in C#检查是否在 C# 中选择了所有单选按钮
【发布时间】:2019-08-11 14:51:29
【问题描述】:

我有大约 75 个单选按钮(在你问为什么需要这么多单选按钮之前,先说我需要它们),我将它们按 5 分组为不同的组。所以,我的问题是,如果在每个组中至少选择一个单选按钮,然后再提交某些内容,有没有一种方法可以验证它们。所以我有 15 个这样的小组。

<h4 style="">1 Question? </h4>

<asp:RadioButton ID="RadioButton1"  runat="server" Text="Strongly Disagree" GroupName="Gr1" />
<asp:RadioButton ID="RadioButton2"  runat="server" Text="Disagree" GroupName="Gr1" />
<asp:RadioButton ID="RadioButton3"  runat="server" Text="Uncertain" GroupName="Gr1" />
<asp:RadioButton ID="RadioButton4"  runat="server" Text="Agree" GroupName="Gr1" />
<asp:RadioButton ID="RadioButton5"  runat="server" Text="Strongly Agree" GroupName="Gr1" />

在后面的代码中,单击按钮时,我会得到类似的东西。这意味着在我使用 SQL 命令提交内容之前,我想首先检查用户是否从每个组中选择了至少一个单选按钮。每个 CMD 都有不同的查询

if (RadioButton1.Checked)
{
    SqlCommand cmd = new SqlCommand("My query here", con);
    cmd.ExecuteNonQuery();
}

if (RadioButton2.Checked)
{
    SqlCommand cmd = new SqlCommand("My query here", con);
    cmd.ExecuteNonQuery();
}

【问题讨论】:

  • 这就是我所拥有的。如果我选择每个单选按钮,它工作正常。我只是不知道是否有办法检查单选按钮是否被选中,我需要强制用户从每个组中选择一个才能提交命令。
  • 然后你应该迭代你的单选按钮,并检查 GroupName 属性,如果从每个 GroupName 中选择一个,他们可以提交,否则抛出错误。如果每个 GroupName 都是唯一的,您可以创建一个 Dictionary 并将键设置为每个 GroupName,如果选中了一个具有该 GroupName 的单选按钮,则将布尔值设置为 true,否则将其保留为 false,然后在迭代后检查你的字典,看看你是否有任何 False 值。
  • 每个 GroupName 都是唯一的,任何代码示例如何做到这一点?
  • 不知道在我的情况下如何实现,:(

标签: c# asp.net sql-server radio-button


【解决方案1】:

以下方法将返回作为父级Control 的直接子级的RadioButton 控件:

private IEnumerable<RadioButton> GetRadioButtons(Control container, string groupName)
{
    return container.Controls
        .OfType<RadioButton>()
        .Where(i => i.GroupName == groupName);
}

例如,如果组名为“Gr1”的单选按钮是您的表单的直接子级,您可以这样获取它们:

var radioButtons = GetRadioButtons(Form, "Gr1");

检查它们是否被检查可以这样完成:

var radioButtonCheckedInGr1 = GetRadioButtons(Form, "Gr1").Any(i => i.Checked);

希望这会有所帮助。

【讨论】:

  • 非常感谢。这完成了工作。它解决了我的问题。这是我一直在寻找的答案。谢谢。干杯
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-21
  • 2016-09-26
  • 2014-04-09
  • 1970-01-01
相关资源
最近更新 更多