简体   繁体   中英

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

I have 11 GroupBoxes and 40 RadioButton in my project. I wanna make when I select a RadioButton in a GroupBox, the other RadioButtons in other GroupBoxes unselect.

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.

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

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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