views:

670

answers:

4

Using WinForms; Is there a better way to find the checked RadioButton for a group? It seems to me that the code below should not be necessary. When you check a different RadioButton then it knows which one to uncheck… so it should know which is checked. How do I pull that information without doing a lot of if statements (or a switch).

     RadioButton rb = null;

     if (m_RadioButton1.Checked == true)
     {
        rb = m_RadioButton1;
     }
     else if (m_RadioButton2.Checked == true)
     {
        rb = m_RadioButton2;
     }
     else if (m_RadioButton3.Checked == true)
     {
        rb = m_RadioButton3;
     }
+2  A: 

Maybe using their events?

CheckedChanged-Event of all RadioButtons
    if ((RadioButton)sender.IsChecked) {
        rb = (RadioButton)sender;
    }
Bobby
+4  A: 

You could use LINQ:

var checkedButton = container.Controls.OfType<RadioButton>()
                                      .FirstOrDefault(r => r.Checked);

Note that this requires that all of the radio buttons be directly in the same container (eg, Panel or Form), and that there is only one group in the container. If that is not the case, you could make List<RadioButton>s in your constructor for each group, then write list.FirstOrDefault(r => r.Checked).

SLaks
I have a Linq book... you just talked me into reading it!
Billy
You really should read it; LINQ is a very powerful tool that can be used in apps that have nothing to do with databases.
SLaks
A: 

You can use the CheckedChanged event for all your RadioButtons. Sender will be the unchecked and checked RadioButtons.

tanascius
+2  A: 

For those without LINQ:

RadioButton GetCheckedRadio(Control container)
{
    foreach (var control in container.Controls)
    {
        RadioButton radio = control as RadioButton;

        if (radio != null && radio.Checked)
        {
            return radio;
        }
    }

    return null;
}
João Angelo