以编程方式禁用所有文本框,datetimepicker,comboboxes

时间:2015-03-11 05:36:49

标签: c# windows winforms textbox

有没有办法可以在表单加载中禁用所有texbox,datetimepicker,combobox?

我的form_load中有一个像这样的条件:

    private void frmTWLeasing_Load(object sender, EventArgs e)
        {
            //this.Text = sTitle;
            this.txtNinja1.Text = sEnable;
            if (sEnable == "Disabled")
            {

                disable all textboxes, datetimepicker, comboboxes or gridviews
            }
            else
            {
               enable all textboxes, datetimepicker, comboboxes or gridviews
            }
        }

我有这么多的文本框,datetimepicker和组合框,包括datagridview,所以有什么语法可以调用所有文本框,datetimepicker,comboboxes,以便我可以一次禁用它吗?很难一个接一个地禁用它。希望你能帮助我们提前谢谢!!

1 个答案:

答案 0 :(得分:1)

您可以使用OfType(),然后在Where()中获取特定类型控件,然后迭代并禁用它们或按照需要启用它们:

 if (sEnable == "Disabled")
 {

    var controls = this.Controls.OfType<Control>().Where(x=>x is TextBox || x is ComboBox || x is DateTimePicker);

    foreach(var control in controls)
          control.Enabled = false;
 }

您需要在班级中添加using System.Linq

如果你有嵌套控件中的控件,意味着在一些用户控件或其他控件中,那么你需要像this SO post (How to get ALL child controls of a Windows Forms form of a specific type)

那样递归检查
相关问题