如何才能更好地一次控制多个控件的行为?

时间:2011-07-25 15:52:06

标签: c# winforms .net-3.5 controls

所以我有一个表单,其中包含一些制表符对象,组对象以及组对象内可能的表格布局面板。

基于数据锁,表单将禁用几乎所有内容,因此我需要将内容标记为只读,这样用户仍然可以看到数据但不能更改...

以下是我必须浏览集合并将对象标记为只读的代码......

    private void lockForm()
    {
        btnLockData.BackColor = Color.LightBlue;
        btnLockData.Text = "Data locked!  Click to unlock...";

        foreach (Control formObject in this.Controls)
        {
            if (formObject is TabControl)
            {
                foreach (Control tabControl in (formObject.Controls))
                {
                    foreach (Control tabPageObject in (tabControl.Controls))
                    {
                        if (tabPageObject is TextBox)
                            ((TextBox)tabPageObject).ReadOnly = true;

                        if (tabPageObject is DataGridView)
                            ((DataGridView)tabPageObject).ReadOnly = true;


                        if (tabPageObject is GroupBox)
                        {
                            foreach (Control groupBoxObject in tabPageObject.Controls)
                            {
                                if (groupBoxObject is TextBox)
                                    ((TextBox)groupBoxObject).ReadOnly = true;

                                if (groupBoxObject is DataGridView)
                                    ((DataGridView)groupBoxObject).ReadOnly = true;

                                if (groupBoxObject is TableLayoutPanel)
                                {
                                    foreach (Control layoutObject in groupBoxObject.Controls)
                                    {
                                        if (layoutObject is TextBox)
                                            ((TextBox)layoutObject).ReadOnly = true;

                                        if (layoutObject is DataGridView)
                                            ((DataGridView)layoutObject).ReadOnly = true;                                            
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        dgvResources.ReadOnly = false;
        dgvDirectLabor.ReadOnly = false;
    }

有没有更好的方法来控制这种行为?

2 个答案:

答案 0 :(得分:3)

要更精细地控制设置Readonly的控件,请尝试:

   this.Controls.Cast<Control>()
        .Where(ctl => ctl is TextBox).Cast<TextBox>().ToList()
        .ForEach(e => e.ReadOnly = true);

    this.Controls.Cast<Control>()
        .Where(ctl => ctl is DataGridView).Cast<DataGridView>().ToList()
        .ForEach(e => e.ReadOnly = true);

答案 1 :(得分:1)

这应该是WinForms的技巧:

var controls = from controls in this.Controls.OfType<Control>()
              select controls;
foreach(c in controls) { c.Enabled = false; }