Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RadioButton and switch

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?

like image 224
Wildhorn Avatar asked Dec 16 '10 13:12

Wildhorn


People also ask

What is the use of Radiobutton control?

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.

What can I use instead of a radio button?

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.

Can radio button have more than 2 options?

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.

Should radio buttons always have a default?

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.


2 Answers

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.

like image 70
Liviu Mandras Avatar answered Sep 24 '22 04:09

Liviu Mandras


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]();
}
like image 42
Fredrik Mörk Avatar answered Sep 22 '22 04:09

Fredrik Mörk