Make all Controls on a Form read-only at once

前端 未结 7 492
故里飘歌
故里飘歌 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:14

    You should be able to write yourself a utility function to do this. You can iterate over the form’s controls and then each control’s child controls recursively. For example:

    public static void SetEnableOnAllControls(Control parentControl, bool enable)
    {
        parentControl.Enabled = enable;
        foreach (Control control in parentControl.Controls)
            SetEnableOnAllControls(control, enable);
    }
    
    [...]
    
    // inside your form:
    SetEnableOnAllControls(this, false);
    

    This doesn’t take care of ToolStrips, which aren’t controls. You could write a separate, similar method for those.

    Notice that the above disables the form itself too. If you don’t want that, try this:

    public static void SetEnableOnAllChildControls(Control parentControl, bool enable)
    {
        foreach (Control control in parentControl.Controls)
        {
            control.Enabled = enable;
            SetEnableOnAllChildControls(control, enable);
        }
    }
    

    If you really meant the ReadOnly property, which is only relevant for TextBoxes, try this:

    public static void SetReadOnlyOnAllControls(Control parentControl, bool readOnly)
    {
        if (parentControl is TextBoxBase)
            ((TextBoxBase) parentControl).ReadOnly = readOnly;
        foreach (Control control in parentControl.Controls)
            SetReadOnlyOnAllControls(control, readOnly);
    }
    

提交回复
热议问题