Original address WinForm Custom Function FindControl implement find control by name
In this paper, the realization of the WinForm Custom function FindControl The function of finding the control by name has some practical value in the development of C # program.
<summary>///find controls by name///</summary>///<param name= "ParentControl" > Find the parent container control of a control </param>/// <param name= "Findctrlname" > Find control Name </param>///<returns> return null</returns>public static if not found Control FindControl (This control ParentControl, string findctrlname) {Control _findedcontrol = null; if (!string. IsNullOrEmpty (findctrlname) && ParentControl! = null) {foreach (Control ctrl in Parentcontrol.controls) {if ( Ctrl. Name.equals (Findctrlname)) {_findedcontrol = ctrl; break; }}} return _findedcontrol;} <summary>///controls to convert a control type///</summary>///<typeparam name= "T" > control type </typeparam>/// <param name= "Control" >control</param>///<param name= "result" > conversion result </param>///<returns > returns the control if successful; Null</returns>public static T cast<t> (this control control, out bool result) if it fails T:cont rol{result = false; T _castctrl = null; if (Control! = null) {if (Control Is t) {try {_castctrl = control as T; result = true; } catch (Exception ex) {Debug.WriteLine (string. Format ("Convert control to some type of exception, reason: {0}", ex.) Message)); result = false; }}} return _castctrl;}
Test code
BOOL _sucess = false; CheckBox _finded = Panel1. FindControl ("CheckBox1"). Cast<checkbox> (out _sucess); if (_sucess) { MessageBox.Show (_finded. Name);} else{ MessageBox.Show ("not finded.");}
[Go] WinForm Custom Function FindControl implement find control by name