手机
当前位置:查字典教程网 >编程开发 >C#教程 >WinForm实现按名称递归查找控件的方法
WinForm实现按名称递归查找控件的方法
摘要:本文所述实例主要实现了WinForm实现按名称递归查找控件的功能,在C#项目开发中有一定的应用价值,分享给大家供大家参考借鉴。关键代码如下:...

本文所述实例主要实现了WinForm实现按名称递归查找控件的功能,在C#项目开发中有一定的应用价值,分享给大家供大家参考借鉴。

关键代码如下:

/// <summary> /// 向下递归查找控件 /// </summary> /// <param name="parentControl">查找控件的父容器控件</param> /// <param name="findCtrlName">查找控件名称</param> /// <returns>若没有查找到返回NULL</returns> public static Control DownRecursiveFindControl(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; } else { if (ctrl.Controls.Count > 0) _findedControl = DownRecursiveFindControl(ctrl, findCtrlName); } } } 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 = this.DownRecursiveFindControl("checkBox1").Cast<CheckBox>(out _sucess); if (_sucess) { MessageBox.Show(_finded.Name); } else { MessageBox.Show("Not Finded."); }

希望本文所述实例能够对大家的C#程序设计有所帮助!

【WinForm实现按名称递归查找控件的方法】相关文章:

C#中隐式运行CMD命令行窗口的方法

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

自定义实现Json字符串向C#对象转变的方法

C# 运用params修饰符来实现变长参数传递的方法

c#实现隐藏与显示任务栏的方法详解

在Winform和WPF中注册全局快捷键实现思路及代码

python实现AutoResetEvent类的阻塞模式方法解析

.net C# 实现任意List的笛卡尔乘积算法代码

c#重写TabControl控件实现关闭按钮的方法

C# WinForm程序完全退出的问题解决

精品推荐
分类导航