如何获取WinForm控件的IsChecked属性?
找不到一个看似简单的问题的答案。 我需要遍历表单上的控件,如果一个控件是一个CheckBox,并且被检查,那么应该完成某些事情。 像这样的东西
foreach (Control c in this.Controls) { if (c is CheckBox) { if (c.IsChecked == true) // do something } }
但我无法访问IsChecked属性。
错误是’System.Windows.Forms.Control’不包含’IsChecked’的定义,并且没有扩展方法’IsChecked’接受类型’System.Windows.Forms.Control’的第一个参数可以找到(你错过了吗?) using指令或程序集引用?)
我怎样才能到达这家酒店? 非常感谢提前!
编辑
好吧,回答所有问题 – 我尝试过铸造,但它不起作用。
你很亲密 您正在寻找的房产是Checked
foreach (Control c in this.Controls) { if (c is CheckBox) { if (((CheckBox)c).Checked == true) // do something } }
您需要将其强制转换为复选框。
foreach (Control c in this.Controls) { if (c is CheckBox) { if ((c as CheckBox).IsChecked == true) // do something } }
您必须从Control添加一个强制转换为CheckBox:
foreach (Control c in this.Controls) { if (c is CheckBox) { if ((c as CheckBox).IsChecked == true) // do something } }
你需要施放控件:
foreach (Control c in this.Controls) { if (c is CheckBox) { if (((CheckBox)c).IsChecked == true) // do something } }
Control类没有定义IsChecked
属性,因此您需要首先将其IsChecked
转换为适当的类型:
var checkbox = c as CheckBox; if( checkbox != null ) { // 'c' is a CheckBox checkbox.IsChecked = ...; }