简体   繁体   中英

C# use switch statement with RadioButton

I want to use the switch method to assign a string value to a variable. I define my variable: string Destination //Then I could use if; else if; else if... but it is too heavy. //I'de like to have: switch (AnyRadioButton is checked) Destination = checked radio button

I assume it would look like that:

switch (????)
case IrelandRaddioButton.Checked = true
Destination = IrelandRadioButton.Text;
Break;

case FranceRaddioButton.Checked = true
Destination = FranceRadioButton.Text;
Break;

case SpainRaddioButton.Checked = true
Destination = SpainRaddioButton.Text;
Break;

And so on... If you could help me writing the correct code for it I'de like to understand better the switch statement and to avoid creating a huge if, else if... Thanks a lot

If (as in the example) the code for each option is the same , you can put it as

  using System.Linq;

  ...

  // Either declare RadioButtons to check or enumerate them 
  // (enumeration depends on whether you use WinForms, WPF, etc.) 
  var buttons = new RadioButton[] {
    IrelandRaddioButton,
    FranceRaddioButton,
    SpainRaddioButton,           
  };

  Destination = buttons.FirstOrDefault(button => button.Checked)?.Text; 

Edit: In case of WinForms you can enumerate all RadioButton s with a help of Controls . Assuming that all RadioButton s of interest are on myPanel (put this if they are on the form)

  var buttons = myPanel
    .Controls()
    .OfType<RadioButton>();

Then compute Destination as usual; you can even combine these queries into one:

  Destination = myPanel
    .Controls()
    .OfType<RadioButton>()
    .FirstOrDefault(button => button.Checked)
   ?.Text;

Note, that now you can add / remove RadioButton s without any code modification

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM