patrick johnsonp
patrick johnsonp

Reputation: 21

How to group radio buttons present in different panels as a single group?

I have to group RadioButtons present in different Panels as a single group. Sa,y for example, I have a RadioButton named radBtn1 on panel1 and radBtn2 and radBtn2 on panel2. Now I want to group all these radio buttons as a single group so that only one RadioButton is checked at a time.

Upvotes: 2

Views: 391

Answers (1)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186668

We can try uncheck RadioButtons manually. Let's assign RadioButtons_CheckedChanged event handler for all RadioButtons of interest:

private void RadioButtons_CheckedChanged(object sender, EventArgs e) {
  // If we have a RadioButton Checked 
  if (sender is RadioButton current && current.Checked) {
    // We should remove Check from the rest RadioButtons:
    var rest = new Control[] { panel1, panel2} 
      .SelectMany(ctrl => ctrl             // all radiobuttons on panel1, panel2
         .Controls
         .OfType<RadioButton>())
      .Where(button => button != current); // don't touch current it should stay checked

    foreach (var button in rest)
      button.Checked = false;
  }
}

Upvotes: 2

Related Questions