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

岁酱吖の 提交于 2019-12-22 09:18:41

问题


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?


回答1:


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




回答2:


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



回答3:


GroupName is property used in Web.UI.RadioButton to group a set of radio butons as one unit. All radiobuttons with same GroupName value will form a group.

This functionality however is not available in winforms.

So the only way to group radiobuttons in winforms will be to keep them together in the same container (generally a groupbox).




回答4:


There is a property called "validation" group or something like that that groups all the controls into one validation. Only one of them is checked only. Other ones uncheck.



来源:https://stackoverflow.com/questions/10073692/how-to-set-radio-buttons-in-a-nested-group-box-as-a-same-group-with-radio-button

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!