C# ForEach 對所有控制項設定唯讀

  • 8060
  • 0
  • C#
  • 2011-05-07

ForEach 對所有控制項設定唯讀

對 所有控制項 設定屬性 這個例子是很常用的

這也是foreach最常使用到的功能

如果是一般的容器 參數就用 容器的name

對表單 用this就可以了

 


        private void Form1_Load(object sender, EventArgs e)
        {
            DisableTextBox(panel1);//針對panel 的textbox checkbox 設定唯讀
            DisableTextBox(this);//針對form1 的textbox checkbox 設定唯讀

        }
        private void button1_Click(object sender, EventArgs e)
        {
            EnableTextBox(panel1);//針對panel
            EnableTextBox(this);//針對form1
        }

        public static void DisableTextBox(Control control)
        {
            if (control.HasChildren)
            {
                foreach (Control subControl in control.Controls)
                {
                    if (subControl is TextBox)
                        (subControl as TextBox).ReadOnly = true;
                    else if (subControl is CheckBox)
                        (subControl as CheckBox).Enabled = false;
                }
            }
        }

        public static void EnableTextBox(Control control)
        {
            if (control.HasChildren)
            {
                foreach (Control subControl in control.Controls)
                {
                    if (subControl is TextBox)
                        (subControl as TextBox).ReadOnly = false;
                    else if (subControl is CheckBox)
                        (subControl as CheckBox).Enabled = true;
                }

            }
        }

範例下載


如有錯誤 歡迎指正