Reputation: 3480
I am using a TableLayoutPanel and anchor property in order to make a window application that will look good independent to the screen resolution or to the form resize. I referred to this article in order to design the winform.
I have 3 RadioButtons
on my form. Until working without TableLayoutPanel
, the RadioButtons
behave as per my expectation. Checking one RadioButton
, unchecking the 2 other ones.
After adding each RadioButton
into different cell of the TableLayoutPanel
, the RadioButtons
behavior changed. Checking a RadioButton
doesn't uncheck the other ones.
Is there any property (group property) that I could set to have the 3 RadioButtons
working together?
Upvotes: 3
Views: 1672
Reputation: 54433
First let me say that the key to a good solution is that you keep up the visual paradigm of buttons that belong to one group; the user must not be surprised by RadioButtons
that interact although they are far apart from each other.. But your layout seems to take care of that alright.
Probably for that very reason there is no property that would allow grouping RBs randomly..
Here is a helper class that manages RadioButtons
indepently of their containers..:
class RadioCtl
{
private List<RadioButton> buttons { get; set; }
private bool auto = false;
public RadioCtl() { buttons = new List<RadioButton>(); }
public int RegisterRB(RadioButton rb)
{
if (!buttons.Contains(rb))
{
buttons.Add(rb);
rb.CheckedChanged += rb_CheckedChanged;
}
return buttons.IndexOf(rb);
}
void rb_CheckedChanged(object sender, EventArgs e)
{
RadioButton rbClicked = sender as RadioButton;
if (rbClicked == null || auto) return;
auto = true;
foreach (RadioButton rb in buttons)
{
if ((rb != rbClicked) && (rb.Parent != rbClicked.Parent) )
rb.Checked = false;
}
auto = false;
}
public void UnregisterRB(RadioButton rb)
{
if (buttons.Contains(rb))
{
buttons.Remove(rb);
rb.CheckedChanged -= rb_CheckedChanged;
}
}
public void Clear() { foreach(RadioButton rb in buttons) UnregisterRB(rb); }
public int IndexOfRB(RadioButton rb) { return buttons.IndexOf(rb); }
}
To use it you need to register each RadioButton
you want to participate in the 'virtual group'..:
static RadioCtl RbCtl = new RadioCtl();
public Form1()
{
InitializeComponent();
RbCtl.RegisterRB(radioButton1);
RbCtl.RegisterRB(radioButton2);
RbCtl.RegisterRB(radioButton3);
RbCtl.RegisterRB(radioButton4);
RbCtl.RegisterRB(radioButton5);
}
You can unregister or re-register any RadioButton
at any time or find the index in the group.
Also note that this only supports one group of RadioButtons
. If you need more, either use a second object or expand the class to allow several, maybe named groups. You could replace the List
by a Dictionary
for this and expand the signatures and the code a little..
Upvotes: 2
Reputation: 2180
Put all radio buttons for a group in a container object like a Panel
or a GroupBox
. That will automatically group them together.
Upvotes: 0