1
\$\begingroup\$

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?

\$\endgroup\$
0
\$\begingroup\$

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

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

switch(radio.Name)
{
    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.

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ You're right, combobox is definitely the way to go here. Your solution is nice though. \$\endgroup\$ – Glazbee Dec 13 '19 at 16:59
2
\$\begingroup\$

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)
{
    RadioButton rb = (RadioButton)sender;
    if(!rb.Checked)
    {
        return;
    }
    selectedButton = rb.Name.Last() - '0';
    selectedButtonText = rb.Text;
}
| improve this answer | |
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.