WinForm Method for Traversing All Child Controls of a Form
- 2021-10-27 08:42:03
- OfStack
This article illustrates the method of WinForm traversing all child controls of a form. Share it for your reference, as follows:
/// <summary>
/// C# Only child controls of the control are traversed, not grandchildren
/// When a control has child controls, you need to iterate recursively to list all the controls on the control
/// </summary>
/// <typeparam name="T"> Control type </typeparam>
/// <param name="control"> Controls to traverse </param>
/// <param name="controlsName"> Control name </param>
/// <returns></returns>
public static T GetControl<T>(Control control, string controlsName) where T : Control
{
if (control == null) return null;
Control _control;
for (int i = 0; i < control.Controls.Count; i++)
{
_control = control.Controls[i];
if (_control == null) return null;
if (_control.Name == controlsName && _control is T)
return (T)_control;
if (_control.HasChildren)
{
_control = GetControl<T>(_control, controlsName);
if (_control != null)
return (T)_control;
}
}
return null;
}
/// <summary>
/// Traverse all child controls of the form
/// </summary>
/// <typeparam name="T"> Control type </typeparam>
/// <param name="form"> Form name </param>
/// <param name="controlsName"> Control name </param>
/// <returns></returns>
public static T GetControl<T>(Form form, string controlsName) where T : Control
{
T _Control = null;
for (int i = 0; i < form.Controls.Count; i++)
{
_Control = GetControl<T>(form.Controls[i], controlsName);
if (_Control != null)
return _Control;
}
return null;
}
More readers interested in C # can check the topic of this site: "WinForm Control Usage Summary", "C # Form Operation Skills Summary", "C # Common Control Usage Tutorial", "C # Programming Thread Use Skills Summary", "C # Operating Excel Skills Summary", "XML File Operation Skills Summary in C #", "C # Data Structure and Algorithm Tutorial", "C # Array Operation Skills Summary" and "C # Object-Oriented Programming Introduction Tutorial"
I hope this article is helpful to everyone's C # programming.