切换所有控件只读按钮单击WinForm

时间:2009-05-26 19:39:02

标签: .net winforms controls loops toggle

我希望能够将表单上的一组控件设置为只读,然后单击按钮返回。有没有办法循环它们? this.Controls也许......

谢谢!

4 个答案:

答案 0 :(得分:5)

如果要将所有控件设置为只读,可以执行以下操作:

foreach(Control currentControl in this.Controls)
{
    currentControl.Enabled = false;
}

如果您真正想要做的是将某些控件设置为只读,我建议保留相关控件的列表,然后在THAT列表上执行ForEach,而不是全部。

答案 1 :(得分:3)

设置启用/禁用很容易,请参阅GWLIosa的答案。

但并非所有控件都具有只读属性。你可以使用类似的东西:

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
}

答案 2 :(得分:2)

我个人将所有想要影响的控件(和子控件)放入Panel - 然后只更改单Panel的状态。这意味着您不必开始存储旧值(将它们放回去 - 例如,您可能不想假设它们都已启用)。

答案 3 :(得分:1)

我建议你使用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);
        }