Which Radio button in the group is checked?(选中组中的哪个单选按钮?)
问题描述
使用 WinForms;有没有更好的方法来为一个组找到选中的 RadioButton?在我看来,下面的代码应该是不必要的.当您选中一个不同的 RadioButton 时,它就会知道要取消选中哪个……所以它应该知道哪个被选中.如何在不执行大量 if 语句(或 switch)的情况下提取这些信息.
Using WinForms; Is there a better way to find the checked RadioButton for a group? It seems to me that the code below should not be necessary. When you check a different RadioButton then it knows which one to uncheck… so it should know which is checked. How do I pull that information without doing a lot of if statements (or a switch).
RadioButton rb = null;
if (m_RadioButton1.Checked == true)
{
rb = m_RadioButton1;
}
else if (m_RadioButton2.Checked == true)
{
rb = m_RadioButton2;
}
else if (m_RadioButton3.Checked == true)
{
rb = m_RadioButton3;
}
推荐答案
你可以使用 LINQ:
You could use LINQ:
var checkedButton = container.Controls.OfType<RadioButton>()
.FirstOrDefault(r => r.Checked);
请注意,这要求所有单选按钮都直接位于同一个容器(例如,面板或表单)中,并且容器中只有一个组.如果不是这种情况,您可以在每个组的构造函数中创建 List
,然后编写 list.FirstOrDefault(r => r.Checked)
.
Note that this requires that all of the radio buttons be directly in the same container (eg, Panel or Form), and that there is only one group in the container. If that is not the case, you could make List<RadioButton>
s in your constructor for each group, then write list.FirstOrDefault(r => r.Checked)
.
这篇关于选中组中的哪个单选按钮?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:选中组中的哪个单选按钮?


- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- 输入按键事件处理程序 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- MoreLinq maxBy vs LINQ max + where 2022-01-01