I have these groupboxes:
I want to run some code according to checked true state of a radio button like:
string chk = radiobutton.nme; // Name of radio button whose checked is true
switch(chk)
{
case "Option1":
// Some code
break;
case "Option2":
// Some code
break;
case "Option3":
// Some code
break;
}
Is there any direct way so that I can only get the name of the checked radio button?
Rather than checking all RadioButtons, use the Validated event of the GroupBox.
You should take some look at the
CheckedChanged
event to register the corresponding event handler and store theChecked
radio button state in some variable. However, I would like to use LINQ here just because you have just someRadioButtons
which makes the cost of looping acceptable:You can find all checked RadioButtons like
Also take a look at
CheckedChanged
event.In my opinion, it's better if you use RadioGroup instead of GroupBox. If you use radioGroup, you can always find the selected item easily like this:
If you design using Windows Forms, I suggest to implement RadioGroup behavior like this (please note that my code is in Java):
You can put this code block in a method to return selected radioButton value, and then you can use this value in your SWITCH part.