Search code examples
c#if-statementradio-button

More elegant way of checking if a RadioButton is checked in C#


I'm working on a Winforms app and I have 5 radio buttons. I need to know which one is checked. Is there a better/more compact way of doing this in C#?

For now I have this:

if (rbtnArgent.Checked)
    return "Silver";
else if (rbtnBleuF.Checked)
    return "Dark Blue";
else if (rbtnBleuP.Checked)
    return "Light Blue";
else if (rbtnJaune.Checked)
    return "Yellow";
else
    return "Pink";

It's working but maybe i will need to add more radio buttons to my form in the future...


Solution

  • Consider setting the Tag property to a color than use the following code to get the checked RadioButton.

    public static class ControlExtensions
    {
        public static IEnumerable<T> Descendants<T>(this Control control) where T : class
        {
            foreach (Control child in control.Controls)
            {
                if (child is T thisControl)
                    yield return thisControl;
                if (!child.HasChildren) continue;
                foreach (T descendant in Descendants<T>(child))
                    yield return descendant;
            }
        }
        public static RadioButton RadioButtonChecked(this Control control, bool @checked = true)
            => control.Descendants<RadioButton>().ToList()
                .FirstOrDefault((radioButton) => radioButton.Checked == @checked);
    
        public static string GetColor(this RadioButton radioButton) 
            => radioButton.Tag.ToString();
    }
    

    Usage in a Button Click event

    var rb = this.RadioButtonChecked();
    
    if (rb is not null)
    {
        MessageBox.Show(rb.GetColor());
    }
    else
    {
        MessageBox.Show("Make a selection");
    }