问题
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