.net 在WinForm中单击按钮时将所有控件切换为只读
我希望能够将表单上的一组控件设置为只读,然后单击按钮返回。有没有办法在它们之间循环<代码>此。控制可能.net 在WinForm中单击按钮时将所有控件切换为只读,.net,winforms,controls,loops,toggle,.net,Winforms,Controls,Loops,Toggle,我希望能够将表单上的一组控件设置为只读,然后单击按钮返回。有没有办法在它们之间循环此。控制可能 谢谢 如果要将所有控件设置为只读,可以执行以下操作: foreach(Control currentControl in this.Controls) { currentControl.Enabled = false; } foreach (Control c in this.Controls) { if (c is TextBox) (c as TextBox).Readonl
谢谢 如果要将所有控件设置为只读,可以执行以下操作:
foreach(Control currentControl in this.Controls)
{
currentControl.Enabled = false;
}
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
}
如果您真正想做的是将某些控件设置为只读,我建议保留一个相关控件的列表,然后在该列表上执行ForEach,而不是所有控件 将其设置为启用/禁用很容易,请参阅GWLIosa'a的答案 但是,并非所有控件都具有只读属性。您可以使用以下内容:
foreach(Control currentControl in this.Controls)
{
currentControl.Enabled = false;
}
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
}
就我个人而言,我会将我想要影响的所有控件(和子控件)放入
面板
——然后只需更改单个面板的状态即可。这意味着您不必开始存储旧值(要将它们放回去,您可能不想假设它们都已启用)。我建议您使用GWLlosa建议的enabled属性,但如果您想要或需要使用ReadOnly属性,请尝试以下操作:
foreach (Control ctrl in this.Controls)
{
Type t = ctrl.GetType();
PropertyInfo propInfo = t.GetProperty("ReadOnly");
if (propInfo != null)
propInfo.SetValue(ctrl, true, null);
}