[WinForm] recursively finds controls by name

Source: Internet
Author: User

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!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.