切换所有控件只读的按钮单击在winform
题
我希望能够设置一堆的窗体上控件为只读和回用点击一个按钮。有没有一种方法,以通过他们循环? this.Controls
也许......
谢谢!
解决方案
如果你想设置的所有控件为只读,你可以这样做:
foreach(Control currentControl in this.Controls)
{
currentControl.Enabled = false;
}
如果你真正想要做的是设置一些控制为只读,我建议保持相关控件的列表,然后做一个foreach在名单上,而不是所有的人。
其他提示
设置它们启用/禁用容易,看到GWLIosa'a答案。
然而,不是所有的控件具有只读属性。你可以使用这样的:
foreach (Control c in this.Controls)
{
if (c is TextBox)
(c as TextBox).Readonly = newValue;
else if (c is ListBox)
(c as ListBox).Readonly = newValue;
// etc
}
我个人会把所有的控制(和子控件)我想影响到Panel
- 然后就改变单一Panel
的状态。这意味着你不必开始储存旧值(把他们回来 - 你可能不想承担他们都开始启用,例如)。
我建议您使用GWLlosa建议Enabled属性,但是如果你想要或需要使用只读属性,尝试这个办法:
foreach (Control ctrl in this.Controls)
{
Type t = ctrl.GetType();
PropertyInfo propInfo = t.GetProperty("ReadOnly");
if (propInfo != null)
propInfo.SetValue(ctrl, true, null);
}
不隶属于 StackOverflow