C# WinForm 按名称查找控件

 1 /// <summary>
 2 /// 按名称查找控件
 3 /// </summary>
 4 /// <param name="parentControl">查找控件的父容器控件</param>
 5 /// <param name="findCtrlName">查找控件名称</param>
 6 /// <returns>若没有查找到返回NULL</returns>
 7 public static Control FindControl(Control parentControl, string findCtrlName)
 8 {
 9     if (!string.IsNullOrEmpty(findCtrlName) && parentControl != null)
10     {
11         foreach (Control ctrl in parentControl.Controls)
12         {
13             Control _findedControl;
14             if (ctrl.Name.Equals(findCtrlName))
15             {
16                 _findedControl = ctrl;
17                 return _findedControl;
18             }
19             else if (ctrl.Controls.Count > 0)
20             {
21                 _findedControl = FindControl(ctrl, findCtrlName);
22                 if (_findedControl != null)
23                 {
24                     return _findedControl;
25                 }
26             }
27         }
28     }
29     return null;
30 }

 

posted @ 2022-09-05 17:01  Mr_Xul  阅读(642)  评论(0编辑  收藏  举报