Radioobuttons - test if checked - why do the first 2 approaches fail?

I was wondering why below doesn't work as expected ... if the if-statement is changed to (! Ctrl.checked) it returns all radio button names)

myForm f = new myForm ();

        foreach (RadioButton ctrl in f.Controls.OfType<RadioButton>())
        {
            if (ctrl.Checked)
                MessageBox.Show(ctrl.Name);
        }

      

I have also tried

        foreach (Control c in f.controls)
            if (c is radiobutton)
            {
                if (c.Checked)
                {
                    messagebox.show(c.name);
                }

      

when i put all radio buttons in groupbox and use below code:

        foreach (RadioButton c in groupBox1.Controls)
        {
            if (c.Checked)
            {
                MessageBox.Show(c.Name);
            }
        }

      

it worked fine.

what's the difference here.

any help appreciated

+3


source to share


1 answer


I am assuming your radio button is a child control other than a form. You need to search for switches recursively.



    public void DisplayRadioButtons()
    {
        Form f = new Form();
        RecursivelyFindRadioButtons(f);
    }

    private static void RecursivelyFindRadioButtons(Control control)
    {
        foreach (Control childControl in control.Controls)
        {
            RecursivelyFindRadioButtons(childControl);
            if (childControl is RadioButton && ((RadioButton) childControl).Checked)
            {
                MessageBox.Show(childControl.Name);
            }
        } 
    }

      

0


source







All Articles