表单上所有文本框的最大长度

Max length for all textboxes on a form

文本框输入值的最大长度可以由 MaxLength 属性 决定。但是我们需要为每个文本框一个一个地做这个。

有没有办法为表单上的所有文本框设置一次 MaxLength 属性 的值?

您可以在 On_Loaded 事件中用代码完成。查询窗体上的所有控件并设置 MaxLength。您还可以基于具有预定义 MaxLength 的 TextBox 创建自定义控件,并使用它代替标准 TextBox。

How to get ALL child controls of a Windows Forms form of a specific type (Button/Textbox)?

是否使用递归调用,因为表单有面板,文本框在面板内。

这是获取表单上所有文本框的扩展方法:

public static IEnumerable<TControl> GetChildControls<TControl>(this Control control) where TControl : Control
       {
           var children = (control.Controls != null) ? control.Controls.OfType<TControl>() : Enumerable.Empty<TControl>();
           return children.SelectMany(c => GetChildControls<TControl>(c)).Concat(children);
       }