How to get the IsChecked property of a WinForm con

2020-02-15 03:45发布

问题:

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.

回答1:

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             
      } 
} 


回答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
            }
        }


回答3:

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
            }
        }


回答4:

You need to cast the control:

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


回答5:

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 = ...;
}