Question

Now that I have your attention ;)

I know group boxes are used to primarily group controls for easy manipulation at design time and in certain cases like Radio Buttons, can group several selections on the same form, but is there a (fairly simple) way of imitating a SelectedIndex() function on a group box?

For example, say I have a group box with 4 radioButtons:

enter image description here

Can I imitate something like this?

// Pseudo Code:

int chosenNumber = groupBox1.SelectedIndex(radioButton.Checked);
Was it helpful?

Solution

Assuming .NET 3.5 or later:

var radioButtons = groupBox1.Controls.OfType<RadioButton>().ToArray();
var selectedIndex = Array.IndexOf(radioButtons, radioButtons.Single(rb => rb.Checked));

You could create your own derived GroupBox class and add a SelectedIndex property that incorporated that code in the getter if you wanted.

Note that that assumes that a RadioButton will always be checked. Use SingleOrDefault if that may not be the case.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top