将表单上的所有控件一次性设置为只读

Nic*_*rca 7 .net c# vb.net winforms

有没有人有一段代码可以在一个Form中制作所有的控件(甚至所有TextBox),它是一次只读的,而不必将每个Control设置为只读?

aba*_*hev 6

编写一个扩展方法,收集指定类型的控件和子控件:

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

在表单上收集TextBoxes(用于TextBoxBase影响RichTextBox等 - @ Timwi的解决方案):

IEnumerable<TextBoxBase> textBoxes = this.GetChildControls<TextBoxBase>();
Run Code Online (Sandbox Code Playgroud)

通过集合迭代并设置只读:

private void AreTextBoxesReadOnly(IEnumerable<TextBoxBase> textBoxes, bool value)
{
    foreach (TextBoxBase tb in textBoxes) tb.ReadOnly = value;
}
Run Code Online (Sandbox Code Playgroud)

如果想要 - 使用缓存 - @ igor的解决方案


gar*_*rik 5

通知:

if (_cached == null)
{
    _cached = new List<TextBox>();

    foreach(var control in Controls)
    {
        TextBox textEdit = control as TextBox;
        if (textEdit != null)
        {
            textEdit.ReadOnly = false;
            _cached.Add(textEdit);
        }
    }
} 
else
{
    foreach(var control in _cached)
    {            
        control .ReadOnly = false;
    }
}
Run Code Online (Sandbox Code Playgroud)

同时添加递归(控件可以放在其他控件(面板)中).