2

Can't find the answer to a seemingly easy question. I need to iterate through the controls on a form, and if a control is a CheckBox, and is checked, certain things should be done. Something like this

foreach (Control c in this.Controls)
        {
            if (c is CheckBox)
            {
                if (c.IsChecked == true)
                    // do something
            }
        }

But I can't reach the IsChecked property.

The error is 'System.Windows.Forms.Control' does not contain a definition for 'IsChecked' and no extension method 'IsChecked' accepting a first argument of type 'System.Windows.Forms.Control' could be found (are you missing a using directive or an assembly reference?)

How can I reach this property? Thanks a lot in advance!

EDIT

Okay, to answer all - I tried casting, it doesn't work.

tube-builder
  • 686
  • 1
  • 13
  • 29

5 Answers5

5

You're close. The property you're looking for is Checked

foreach (Control c in this.Controls) {             
   if (c is CheckBox) {
      if (((CheckBox)c).Checked == true) 
         // do something             
      } 
} 
Jay Riggs
  • 53,046
  • 9
  • 139
  • 151
2

You need to cast it to checkbox.

foreach (Control c in this.Controls)
        {
            if (c is CheckBox)
            {
                if ((c as CheckBox).IsChecked == true)
                    // do something
            }
        }
Anuraj
  • 18,859
  • 7
  • 53
  • 79
1

You have to add a cast from Control to CheckBox:

foreach (Control c in this.Controls)
        {
            if (c is CheckBox)
            {
                if ((c as CheckBox).IsChecked == true)
                    // do something
            }
        }
1

You need to cast the control:

    foreach (Control c in this.Controls)
    {
        if (c is CheckBox)
        {
            if (((CheckBox)c).IsChecked == true)
                // do something
        }
    }
faester
  • 14,886
  • 5
  • 45
  • 56
1

The Control class does not define an IsChecked property, so you will need to cast it to the appropriate type first:

var checkbox = c as CheckBox;
if( checkbox != null )
{
    // 'c' is a CheckBox
    checkbox.IsChecked = ...;
}
Ed S.
  • 122,712
  • 22
  • 185
  • 265
  • you mean **checkbox** and not **c** – V4Vendetta Apr 05 '11 at 07:09
  • Only vindictive about bad answers. Control does indeed not define `IsChecked` property, but neither does CheckBox. – drharris Apr 05 '11 at 07:12
  • I assumed WPF when I saw IsChecked along with the fact that the OP's example uses a CheckBox and the IsChecked property, but you're right; it is tagged WinForms. – Ed S. Apr 05 '11 at 07:13