c# - 检查是否在 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();
}
解决方案
以下方法将为您返回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);
希望这可以帮助。
推荐阅读
- operating-system - 单个应用程序实例
- amazon-web-services - Route53 + CloudFront + ELB + Apache2
- android - 如何使用房间 android kotlin 获取最后插入的行 ID?
- javascript - 使用数组作为输入时,如何在 dygraphs 中获取误差线和滚动窗口?
- node.js - 如何从节点发送响应以响应渲染特定组件?
- vba - 将 OLE 对象(图像)从 accdb 文件导出到文件夹
- mongodb - 无论如何知道任何数据库集合已在 mongodb 中更新?
- match - DESeq2 - 组织数据 - 计算列数多于元数据行的数据,删除数据集之间不匹配的 TCGA ID
- javascript - 创建一个具有自动填充逗号或点到浮点字段功能的小部件(Odoo 13)
- javascript - 如何为以下标准编写语法 - ANTLR4 语法 - 自定义表达式