Search code examples
c#winformsradio-buttongroupbox

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.


Solution

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