首页 > 解决方案 > 检查是否在 C# 中选择了所有单选按钮

问题描述

我有大约 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();
}

标签: c#asp.netsql-serverradio-button

解决方案


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

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);

希望这可以帮助。


推荐阅读