实现按名称递归查找控件的方法WinForm

本文所述实例主要实现了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转换某种控www.wolaix.com件类型
/// </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.Showww.fanyaylc.comw(_finded.Name);
}
else
{
 MessageBox.Show("Not Finded.");
}

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值