Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set radio buttons in a nested group box as a same group with radio buttons outside of that group box [duplicate]

I have winform application (.NET 4.0)

Is there any way to manually set a group of radio buttons?

I have four radio buttons, two of them inside of a group box and the other two outside of that box. How can I set all of them to the same group?

like image 735
Tae-Sung Shin Avatar asked Jan 17 '23 23:01

Tae-Sung Shin


2 Answers

This might have been answered in another post, it sounds the same:

Grouping Windows Forms Radiobuttons with different parent controls in C#

This was the accepted solution:

I'm afraid you'll have to handle this manually... It's not so bad actually, you can probably just store all the RadioButton in a list, and use a single event handler for all of them:

private List<RadioButton> _radioButtonGroup = new List<RadioButton>();
private void radioButton_CheckedChanged(object sender, EventArgs e)
{
    RadioButton rb = (RadioButton)sender;
    if (rb.Checked)
    {
        foreach(RadioButton other in _radioButtonGroup)
        {
            if (other == rb)
            {
                continue;
            }
            other.Checked = false;
        }
    }
}

Edit: Here's another question asking the same thing: Radiobuttons as a group in different panels

like image 81
Philip Wallace Avatar answered Jan 31 '23 02:01

Philip Wallace


I'm not sure if this is possible in WinForms.

According to the docs:

All RadioButton controls in a given container, such as a Form, constitute a group.

You could create the class yourself though

public class ButtonGroup {
   private IList<RadioButton> radiogroup;

   public ButtonGroup(IEnumerable<RadioButton> selection) {
      radiogroup = new List<RadioButton>(selection);
      foreach (RadioButton item in selection) {
          item.CheckedChanged += uncheckOthers;
      }
   }

   private void uncheckOthers(object sender, EventArgs e) {
      if (((RadioButton)sender).Checked) {
        foreach (RadioButton item in radiogroup) {
          if (item != sender) { item.Checked = false; }
        }
      }
   }
}
like image 30
Patrick Avatar answered Jan 31 '23 01:01

Patrick