简体   繁体   English

C#-如果在GroupBox中选择了单选按钮,请在其他GroupBox中取消选择其他单选按钮

[英]C# - If A Radiobutton Selected In GroupBox, Unselect Other Radiobuttons In Other GroupBoxes

I have 11 GroupBoxes and 40 RadioButton in my project. 我的项目中有11个GroupBox和40个RadioButton。 I wanna make when I select a RadioButton in a GroupBox, the other RadioButtons in other GroupBoxes unselect. 我想在GroupBox中选择一个RadioButton时,取消选择其他GroupBox中的其他RadioButtons。

You can recursively search the Form for all RadioButtons, then wire them up and use code like suggested in the linked question from the comments. 您可以递归地在“表单”中搜索所有RadioButton,然后将它们连接起来并使用注释中链接问题中建议的代码。

It might look something like: 它可能看起来像:

public partial class Form1 : Form
{

    public Form1()
    {
        InitializeComponent();
        FindRadioButtons(this);
    }

    private List<RadioButton> RadioButtons = new List<RadioButton>();

    private void FindRadioButtons(Control curControl)
    {
        foreach(Control subControl in curControl.Controls)
        {
            if (subControl is RadioButton)
            {
                RadioButton rb = (RadioButton)subControl;
                rb.CheckedChanged += Rb_CheckedChanged;
                RadioButtons.Add(rb);
            }
            else if(subControl.HasChildren)
            {
                FindRadioButtons(subControl);
            }
        }
    }

    private void Rb_CheckedChanged(object sender, EventArgs e)
    {
        RadioButton source = (RadioButton)sender;
        if (source.Checked)
        {
            RadioButtons.Where(rb => rb != source).ToList().ForEach(rb => rb.Checked = false);
        }          
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM