2015年3月26日 星期四

Asp.net 將所有物件變ReadOnly,及變回來

目前很少直接使用asp.net的control
大多使用jquery + html方式來做
同事問到是否能將所有control變readonly
花了幾分鐘寫了以下的function希望對大家有幫助
變ReadOnly
  void ReadOnlyControl(Control control)
        {
            foreach (var item in control.Controls)
            {
                if (item is System.Web.UI.WebControls.TextBox)
                {
                    TextBox ctrl = (TextBox)item;
                    ctrl.ReadOnly = true;
                }
                else if (item is System.Web.UI.WebControls.DropDownList)
                {
                    DropDownList ctrl = (DropDownList)item;
                    ctrl.Enabled = false;
                }
                else if (item is System.Web.UI.WebControls.CheckBox)
                {
                    CheckBox ctrl = (CheckBox)item;
                    ctrl.Enabled = false;
                }
            }
        }        
變回來
 void WriteControl(Control control)
        {
            foreach (var item in control.Controls)
            {
                if (item is System.Web.UI.WebControls.TextBox)
                {
                    TextBox ctrl = (TextBox)item;
                    ctrl.ReadOnly = false;
                }
                else if (item is System.Web.UI.WebControls.DropDownList)
                {
                    DropDownList ctrl = (DropDownList)item;
                    ctrl.Enabled = true;
                }
                else if (item is System.Web.UI.WebControls.CheckBox)
                {
                    CheckBox ctrl = (CheckBox)item;
                    ctrl.Enabled = true;
                }
            }
        }

使用方式
ReadOnlyControl(form1);
WriteControl(form1);