Key code:
// <summary> /// down recursive lookup control // </summary> // <param name= "ParentControl" > Find control's parent container control </param> /// <param name= "Findctrlname" > Find control Name </param> // <returns> if not found return null</returns> Public StaticControl Downrecursivefindcontrol ( ThisControl ParentControl,stringFindctrlname) {Control _findedcontrol =NULL;if(!string. IsNullOrEmpty (findctrlname) && ParentControl! =NULL) {foreach(Control CtrlinchParentcontrol.controls) {if(CTRL. Name.equals (Findctrlname)) {_findedcontrol = CTRL; Break; }Else{if(CTRL. Controls.Count > 0) _findedcontrol = Downrecursivefindcontrol (ctrl, Findctrlname); } } }return_findedcontrol; }// <summary> /// convert control to a type of controls // </summary> // <typeparam name= "T" > control type </typeparam> /// <param name= "Control" >Control</param> // <param name= "result" > Conversion results </param> // <returns> Returns the control if successful, or null</returns> if it fails Public StaticT cast<t> ( ThisControl control, out BOOLResultwhereT:control {result =false; T _castctrl =NULL;if(Control! =NULL) {if(Control isT) {Try{_castctrl = control asT result =true; }Catch(Exception ex) {Debug.WriteLine (string. Format ("Control is converted to some type of exception, cause: {0}", ex. Message)); result =false; } } }return_castctrl; }
Test code:
bool _sucess = false ; CheckBox _finded = this . Downrecursivefindcontrol ( "CheckBox1" ). Cast<checkbox> (out _sucess); if (_sucess) {MessageBox.Show (_finded). Name); } else {MessageBox.Show ( "not finded.") ); }
Want to help!