SoFunction
Updated on 2025-03-06

WinForm implements a method of recursively searching controls by name

The examples described in this article mainly implement WinForm's function of recursively searching controls by name, and have certain application value in C# project development. I will share it with you for your reference.

The key code is as follows:

/// <summary>
/// Recursively searching down the control/// </summary>
/// <param name="parentControl">Find the control's parent container control</param>/// <param name="findCtrlName">Find control name</param>/// <returns> If no search is found, return NULL</returns>public static Control DownRecursiveFindControl(this Control parentControl, string findCtrlName)
{
  Control _findedControl = null;
  if (!(findCtrlName) &amp;&amp; parentControl != null)
  {
 foreach (Control ctrl in )
 {
   if ((findCtrlName))
   {
 _findedControl = ctrl;
 break;
   }
   else
   {
 if ( &gt; 0)
   _findedControl = DownRecursiveFindControl(ctrl, findCtrlName);
   }
 }
  }
  return _findedControl;
}
/// &lt;summary&gt;
/// Convert Control to some control type/// &lt;/summary&gt;
/// <typeparam name="T">Control type</typeparam>/// &lt;param name="control"&gt;Control&lt;/param&gt;
/// <param name="result">Conversion result</param>/// <returns> Return the control if successful; return NULL if failed</returns>public static T Cast&lt;T&gt;(this Control control, out bool result) where T : Control
{
  result = false;
  T _castCtrl = null;
  if (control != null)
  {
 if (control is T)
 {
   try
   {
 _castCtrl = control as T;
 result = true;
   }
   catch (Exception ex)
   {
 (("WillControlConvert a certain control type exception,reason:{0}", ));
 result = false;
   }
 }
  }
  return _castCtrl;
}

The test code is as follows:

bool _sucess = false;
CheckBox _finded = ("checkBox1").Cast<CheckBox>(out _sucess);
if (_sucess)
{
 (_finded.Name);
}
else
{
 ("Not Finded.");
}

I hope that the examples described in this article can be helpful to everyone's C# programming!