# Is there a better/cleaner way to assign values based on the result of radio buttons?

I have 3 radio buttons all grouped inside a group box in a WinForms project. Currently, I am checking which button is checked and assigning values using the following if/else statement, similar to the below example

        if (rb1.Checked)
{
selectedButton = 1;
selectedButtonText = rb1.Text;
}
else if (rb2.Checked)
{
selectedButton = 2;
selectedButtonText = rb2.Text;
}
else
{
selectedButton = 3;
selectedButtonText = rb3.Text;
}

Console.WriteLine(selectedButtonText);


This doesn't look very efficient or scalable. Is there a better way to do this?

you can use LINQ with Controls to get the checked one.

var radio = groupBox.Controls.OfType<RadioButton>().FirstOrDefault(r => r.Checked);

{
case "rb1":
selectedButton = 1;
selectedButtonText = rb1.Text;
break;
case "rb2":
selectedButton = 2;
selectedButtonText = rb2.Text;
break;
default:
selectedButton = 3;
selectedButtonText = rb3.Text;
break;
}

Console.WriteLine(selectedButtonText);


However, I think you're best if you use something like ComboBox instead of the radio buttons.

• You're right, combobox is definitely the way to go here. Your solution is nice though. Dec 13 '19 at 16:59

Just a side note for you. It would probably be more efficient to use the Checked_Change handler. The main caveat is that both the checked and the unchecked will trigger this event. but since the unchecked is handled first, it's a simple matter of returning if the sender isn't checked.

Since the radiobuttons are actually numbered you don't need the switch block once you have the checked radiobutton identified.

Something like this would work:

private void radioButton_CheckedChanged(object sender, EventArgs e)
{
if(!rb.Checked)
{
return;
}
selectedButton = rb.Name.Last() - '0';
selectedButtonText = rb.Text;
}