I have many radio buttons so I end up with code that look like this
if (rbFrenchImp.Checked)
{
}
else if (rbFrenchMet.Checked)
{
}
else if (rbEnglishImp.Checked)
{
}
else if (rbFrenchEuro.Checked)
{
}
//etc...
So I was wondering, is it possible to use a switch case with radio button? If yes how?
A radio button or option button is a graphical control element that allows the user to choose only one of a predefined set of mutually exclusive options. The singular property of a radio button makes it distinct from checkboxes, where the user can select and unselect any number of items.
Radio buttons and checkboxes are very similar, except for a few key differences. The primary difference is that with radio buttons you can only select one item, while with checkboxes you can select any number.
Radio buttons are normally presented in radio groups (a collection of radio buttons describing a set of related options). Only one radio button in a group can be selected at the same time.
Always Offer a Default Selection One of the 10 heuristics of UI design says that users should be able to undo (and redo) their actions. This means enabling people to set a UI control back to its original state. In case of radio buttons this means that radio buttons should always have exactly one option pre-selected.
Yes you can:
You subcribe the same CheckChanged(or similar) event handler to each of the radio buttons. Then you put some code like this:
RadioButton btn = sender as RadioButton;
if(btn!= null && btn.IsChecked)
{
Switch(btn.Name)
{
case "rbFrenchImpl":
break;
...
}
}
This works on all type of frameworks.
Feels slightly hacky, but you could set up a Dictionary<RadioButton, Action>
containing a mapping between RadioButton
controls and corresponding methods (that are parameterless void
methods, matching the Action
delegate signature):
Dictionary<RadioButton, Action> _rbMethods = new Dictionary<RadioButton, Action>();
When loading the form, add the buttons and corresponding methods to the map:
_rbMethods.Add(rbFrenchImp, FrenchImpAction);
_rbMethods.Add(rbFrenchMet, FrenchMetAction);
_rbMethods.Add(rbEnglishImp, EnglishImpAction);
Then, you can quite easily invoke corresponding methods for the checked radio button (or buttons, in case they are in different groups):
foreach (RadioButton key in _rbMethods.Keys.Where(rb => rb.Checked))
{
_rbMethods[key]();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With