How to get the IsChecked property of a WinForm control?

梦想的初衷 提交于 2019-11-28 10:51:19

问题


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


来源:https://stackoverflow.com/questions/5548308/how-to-get-the-ischecked-property-of-a-winform-control

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!