本文所述實例實現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.");}
希望本文實例對大家C#學習能有所幫助!
新聞熱點
疑難解答