Reputation: 556
I have a form with a number of radiobuttons where only one should be selected at a time.
Some of the radiobuttons are connected and need to bee explained by a header. For this i put them in a Groupbox. But then is the radiobuttons inside the groupbox no longer connected to the ones outside and its possible to select two off them.
Is there a way to connect the radiobuttons so they all react on eachother? Or is there a better way to group and explain the radiobuttons then using a groupbox?
Upvotes: 3
Views: 26494
Reputation: 1
I solved this by handling the CheckChanged event.
private void radio1_CheckedChanged(object sender, EventArgs e)
{
if (radio1.Checked)
{
// do stuff
radio2.Checked = false;
}
}
private void radio2_CheckedChanged(object sender, EventArgs e)
{
if (radio2.Checked)
{
// do stuff
radio1.Checked = false;
}
}
Upvotes: 0
Reputation: 942328
This is possible, but it comes at a high price. You'll have to set their AutoCheck property to false and take care of unchecking other buttons yourself. The most awkward thing that doesn't work right anymore is tab stops, a grouped set of buttons has only one tabstop but if you set AutoCheck = false then every button can be tabbed to.
The biggest problem no doubt it is the considerable confusion you'll impart on the user. So much so that you probably ought to consider checkboxes instead.
Upvotes: 3
Reputation: 54562
It is the designed behavior of a RadioButton to be grouped by its container according to MSDN:
When the user selects one option button (also known as a radio button) within a group, the others clear automatically. All RadioButton controls in a given container, such as a Form, constitute a group. To create multiple groups on one form, place each group in its own container, such as a GroupBox or Panel control
You could try using a common eventhandler for the RadioButtons that you want linked and handle the Checking/UnChecking yourself, Or you can place your RadioButtons on top of your GroupBox, not adding them to the GroupBox then BringToFront.
Upvotes: 5
Reputation: 12544
In windows forms I don't think there is an easy way (as in setting a property such as GroupName) to group radiobuttons. The quickest way would be to simply group the radiobuttons in a collection and listen to the checkedchanged event. For example:
var rbuttons = new List<RadioButton>{ radioButton1, radioButton2, radioButton3, radioButton4 }; //or get them dynamically..
rbuttons.ForEach(r => r.CheckedChanged += (o, e) =>
{
if (r.Checked) rbuttons.ForEach(rb => rb.Checked = rb == r);
});
If any of the radiobuttons in the list is checked, the others are automatically unchecked
Upvotes: 2