Make all Controls on a Form read-only at once

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

    Write an extension method which gathers controls and child controls of specified type:

    public static IEnumerable GetChildControls(this Control control) where T : Control
    {
        var children = control.Controls.OfType();
        return children.SelectMany(c => GetChildControls(c)).Concat(children);
    }
    

    Gather TextBoxes on the form (use TextBoxBase to affect RichTextBox, etc - @Timwi's solution):

    IEnumerable textBoxes = this.GetChildControls();
    

    Iterate thru collection and set read-only:

    private void AreTextBoxesReadOnly(IEnumerable textBoxes, bool value)
    {
        foreach (TextBoxBase tb in textBoxes) tb.ReadOnly = value;
    }
    

    If want - use caching - @igor's solution

提交回复
热议问题