i want to find an index of a selected RadioButton in RadioGroup. I attached next single method to each RadioButton in the group:
private void radio_button_CheckedChanged(object sender, EventArgs e){
if (sender.GetType() != typeof(RadioButton)) return;
if (((RadioButton)sender).Checked){
int ndx = my_radio_group.Controls.IndexOf((Control)sender);
// change something based on the ndx
}
}
It is important to me that lower radioButton must have lower index, starting from zero. And seems it is working, but i am not sure if this is a good solution. Maybe there is more betufilul way to do the same.
This will give you the Checked
RadioButton
:
private void radioButtons_CheckedChanged(object sender, EventArgs e)
{
RadioButton rb = sender as RadioButton;
if (rb.Checked)
{
Console.WriteLine(rb.Text);
}
}
Any indices in the Controls collection of its Parent
are highly volatile.
You could access it like this: rb.Parent.Controls.IndexOf(rb)
If you want a relatively stable ID besides the Name
and the Text
you can put it in the Tag
.
Obviously you need to hook up this event to all the RadionButtons
in the group.
No type checks are really necessary (or imo recommended,) as only a RadioButton
can (or rather: must ever) trigger this event.