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) && parentControl != null) { foreach (Control ctrl in ) { if ((findCtrlName)) { _findedControl = ctrl; break; } else { if ( > 0) _findedControl = DownRecursiveFindControl(ctrl, findCtrlName); } } } return _findedControl; } /// <summary> /// Convert Control to some control type/// </summary> /// <typeparam name="T">Control type</typeparam>/// <param name="control">Control</param> /// <param name="result">Conversion result</param>/// <returns> Return the control if successful; return NULL if failed</returns>public static T Cast<T>(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!