首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >选中组中的哪个单选按钮?

选中组中的哪个单选按钮?
EN

Stack Overflow用户
提问于 2009-11-25 23:57:49
回答 11查看 330.6K关注 0票数 126

使用WinForms;是否有更好的方法来查找组的选中RadioButton?在我看来,下面的代码应该是不必要的。当您选中一个不同的RadioButton时,它就会知道取消选中哪个…因此,它应该知道选中了哪一个。如何在不执行大量if语句(或switch)的情况下提取这些信息。

代码语言:javascript
复制
     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;
     }
EN

回答 11

Stack Overflow用户

回答已采纳

发布于 2009-11-26 00:02:46

您可以使用LINQ:

代码语言:javascript
复制
var checkedButton = container.Controls.OfType<RadioButton>()
                                      .FirstOrDefault(r => r.Checked);

请注意,这要求所有单选按钮都直接位于同一容器中(例如,Panel或Form),并且容器中只有一个组。如果不是这样,您可以在构造函数中为每个组创建List<RadioButton>,然后编写list.FirstOrDefault(r => r.Checked)

票数 228
EN

Stack Overflow用户

发布于 2009-11-26 00:01:28

您可以针对一个处理程序连接所有按钮的CheckedEvents。在那里,您可以很容易地获得正确的复选框。

代码语言:javascript
复制
// Wire all events into this.
private void AllCheckBoxes_CheckedChanged(Object sender, EventArgs e) {
    // Check of the raiser of the event is a checked Checkbox.
    // Of course we also need to to cast it first.
    if (((RadioButton)sender).Checked) {
        // This is the correct control.
        RadioButton rb = (RadioButton)sender;
    }
}
票数 40
EN

Stack Overflow用户

发布于 2009-11-26 00:09:57

对于那些没有LINQ的用户:

代码语言:javascript
复制
RadioButton GetCheckedRadio(Control container)
{
    foreach (var control in container.Controls)
    {
        RadioButton radio = control as RadioButton;

        if (radio != null && radio.Checked)
        {
            return radio;
        }
    }

    return null;
}
票数 26
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/1797907

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档