All, I have a GroupBox with multiple controls (Buttons, RadioButtons etc.) and I want to know the most efficent way of establishing which RadioButton in the GroupBox is in the checked state. I currently have
int nCheckedRadioIdx = 0;
foreach (Control ctrl in groupBoxList.Controls)
{
if (ctrl.GetType() == typeof(RadioButton))
{
if (((RadioButton)ctrl).Checked)
{
switch (((RadioButton)ctrl).Name)
{
case "radioButtonGoodCodeSumm":
nCheckedRadioIdx = 0;
break;
case "radioButtonBadCodeSumm":
nCheckedRadioIdx = 1;
break;
case "radioButtonBadByEpiNo":
nCheckedRadioIdx = 2;
break;
case "radioButtonValidCodes":
nCheckedRadioIdx = 3;
break;
default:
break;
}
break;
}
}
}
I then use an enumerator to establish which button I need. This seems very verbose to me (in fact damn ugly!). I have seen this done in VB with some sort of LINQ query (SO Question) but I have never worked with VB or LINQ and am struggling with the conversion. If there is an even better way that would be great as one of the GroupBoxs contains a significant number of RadioButtons – I would like to use LINQ for this if possible?
Suppose you have, for each radiobutton THE SAME event handler that, when the button is checked set the Tag property of your GroupBox to the Tag of your RadioButton. At design time you set the Tag of the RadioButton to your desidered enum value. When you wish to retrieve your checked button you have only to read the Tag property without going through a loop (elegant or less) to check every control in your GroupBox.
For example:
Of course this will be efficient, but you should be sure to well document this because a change in the enum change will create problems.