Make all Controls on a Form read-only at once

前端 未结 7 487
故里飘歌
故里飘歌 2021-01-12 07:40

Does anyone have a piece of code to make all Controls (or even all TextBoxes) in a Form which is read-only at once without having to set every Control to read-only individua

7条回答
  •  迷失自我
    2021-01-12 08:09

    I just developed a recursive solution that handles any kind of Web Control, using a simple static method and ASP.NET polymorphysm.

    /// 
    /// Handle "Enabled" property of a set of Controls (and all of the included child controls through recursivity)
    /// By default it disable all, making all read-only, but it can also be uset to re-enable everything, using the "enable" parameter 
    /// 
    /// Set of controls to be handled. It could be the entire Page.Controls set or all of the childs of a given control (property "Controls" of any Control-derived class)
    /// Desired value of the property "enable" of each control. 
    public static void DisableControls(ControlCollection controls, bool enable = false)
    {
        foreach (Control control in controls)
        {
            var wCtrl = control as WebControl;
            if (wCtrl != null)
            {
                wCtrl.Enabled = enable;
            }
    
            if (control.Controls.Count > 0)
                DisableControls(control.Controls, enable);
        }
    }
    
    /// 
    /// Enable a set of Controls (and all of the included child controls through recursivity).
    /// Friendly name for DisableControls(controls, true), that achieve the same result.
    /// 
    /// Set of controls to be handled. It could be the entire Page.Controls set or all of the childs of a given control (property "Controls" of any Control-derived class)
    public static void EnableControls(ControlCollection controls)
    {
        DisableControls(controls, true);
    }
    

    This is tested and looks fairly fast (less than a millisecond in a web form with 25+ controls to be disabled).

    If you prefer an extension method, i think it should be enough to change the solution as follows:

    public static void DisableControls(this Control control, bool enable = false)
    {
        foreach (Control ctrl in control.Controls)
        {
            var wCtrl = ctrl as WebControl;
            if (wCtrl != null)
            {
                wCtrl.Enabled = enable;
            }
    
            if (ctrl.Controls.Count > 0)
                ctrl.DisableControls(enable);
        }
    }
    
    public static void EnableControls(this Control control)
    {
        control.DisableControls(true);
    }
    

提交回复
热议问题