手机
当前位置:查字典教程网 >编程开发 >C#教程 >WinForm自定义函数FindControl实现按名称查找控件
WinForm自定义函数FindControl实现按名称查找控件
摘要:本文所述实例实现WinForm自定义函数FindControl实现按名称查找控件的功能,在C#程序开发中有一定的实用价值。分享给大家供大家参...

本文所述实例实现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#学习能有所帮助!

【WinForm自定义函数FindControl实现按名称查找控件】相关文章:

C# WinForm中Panel实现用鼠标操作滚动条的实例方法

C#设计模式之外观模式介绍

浅谈关于C#的垃圾回收机制

深入解析c#中枚举类型的定义与使用

C#处理JPEG头信息的方法

C# Winform 实现屏蔽键盘的win和alt+F4的实现代码

基于运算符重载的那些事

c# winform取消右上角关闭按钮的实现方法

解析如何正确使用SqlConnection的实现方法

c#中var关键字用法浅谈

精品推荐
分类导航