Key code:
// <summary> /// Find control by name // </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 FindControl ( ThisControl ParentControl,stringFindctrlname) {Control _findedcontrol =NULL;if(!string. IsNullOrEmpty (findctrlname) && ParentControl! =NULL) {foreach(Control CtrlinchParentcontrol.controls) {if(CTRL. Name.equals (Findctrlname)) {_findedcontrol = CTRL; Break; } } }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 = Panel1. FindControl ( "CheckBox1" ). Cast<checkbox> (out _sucess); if (_sucess) {MessageBox.Show (_finded). Name); } else {MessageBox.Show ( "not finded.") ); }
Want to help!