[英]C# Foreach to change certain object properties?
I have a panel with checkboxes and labels, I want to change all the checked states of the checkboxes when I click a button. 我有一个带复选框和标签的面板,我想在单击按钮时更改复选框的所有选中状态。
foreach (object x in panel1.Controls)
{
if (x.GetType() == typeof(CheckBox))
{
x.Checked = false; // problem is here;
// (CheckBox)x.Checked = false; // also didn't work
}
}
I'm certain it's something simple but couldn't find how to resolve the issue. 我确信它很简单但无法找到解决问题的方法。 I was able to write the same procedure in vb.net but don't want to use that 我能够在vb.net中编写相同的程序,但不想使用它
您需要在整个转换操作周围加上括号:
((CheckBox)x).Checked = false;
You could definitely clean up your code a bit (as well as resolve the issue with parenthesis): 您肯定可以稍微清理一下代码(以及用括号解决问题):
foreach(var x in panel1.Controls)
{
var checkbox = x as Checkbox;
if(checkbox != null) checkbox.Checked = false;
}
foreach(Checkbox box in panel1.Controls.OfType<CheckBox>())
{
box.Checked = true;
}
Try 尝试
((CheckBox)x).Checked = false;
As you wrote it, the compiler understand 正如你所写,编译器理解
(CheckBox)(x.Checked) = false;
x仍然是一个对象,因此您需要将对象强制转换为复选框
((Checkbox)x).Checked = false;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.