开发者

How to get the IsChecked property of a WinForm control?

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.


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


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


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


You need to cast the control:

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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜