[Go] WinForm Custom Function FindControl implement find control by name

Source: Internet
Author: User

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

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.