[原]c#winformcontrols查指定类型⼦控件的扩展⽅法//调⽤
this.Controls.Find<Button>(true).ForEach((btn) => { btn.Enabled = false; });
//定义
public static class FormControlExtensions
{
/// <summary>
/// 获得指定类型的孩⼦控件
/// </summary>
/// <typeparam name="TChild">⼦控件类型</typeparam>
/// <param name="controlCollection"></param>
/// <param name="searchAllChildren">如果搜索所有⼦控件,则为 true;否则为 false。默认为false。</param>
/// <returns></returns>
public static List<TChild> Find<TChild>(this Control.ControlCollection controlCollection, bool searchAllChildren = false)
where TChild : Control
{
var children = new List<TChild>();
_Find(controlCollection, ref children, searchAllChildren);
return children;
}
/// <summary>
/// 查询指定类型的⼦控件(⽀持递归)
/// </summary>
/// <typeparam name="TChild">⼦控件类型</typeparam>
/// <param name="controlCollection"></param>
/// <param name="children"></param>
/// <param name="searchAllChildren">如果搜索所有⼦控件,则为 true;否则为 false。默认为false。</param>
private static void _Find<TChild>(Control.ControlCollection controlCollection, ref List<TChild> children, bool searchAllChildren = false)
where TChild : Control
{
foreach (Control control in controlCollection)
{
if (control is TChild)
winform增删改查简单案例{
children.Add((TChild)control);
}
if (control.Controls.Count > 0 && searchAllChildren)
{
_Find(control.Controls, ref children, searchAllChildren);
}
}
}
}