[轉] WinForm自訂函數FindControl實現按名稱尋找控制項

來源:互聯網
上載者:User

標籤:

原文地址 WinForm自訂函數FindControl實現按名稱尋找控制項

本文所述執行個體實現WinForm自訂函數FindControl實現按名稱尋找控制項的功能,在C#程式開發中有一定的實用價值。

/// <summary>/// 按名稱尋找控制項/// </summary>/// <param name="parentControl">尋找控制項的父容器控制項</param>/// <param name="findCtrlName">尋找控制項名稱</param>/// <returns>若沒有尋找到返回NULL</returns>public static 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>/// 將Control轉換某種控制項類型/// </summary>/// <typeparam name="T">控制項類型</typeparam>/// <param name="control">Control</param>/// <param name="result">轉換結果</param>/// <returns>若成功則返回控制項;若失敗則返回NULL</returns>public static T Cast<T>(this Control control, out bool result) where T : Control{  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("將Control轉換某種控制項類型異常,原因:{0}", ex.Message));        result = false;      }    }  }  return _castCtrl;}

 測試代碼

bool _sucess = false;CheckBox _finded = panel1.FindControl("checkBox1").Cast<CheckBox>(out _sucess);if (_sucess){    MessageBox.Show(_finded.Name);}else{    MessageBox.Show("Not Finded.");}

 

[轉] WinForm自訂函數FindControl實現按名稱尋找控制項

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.