当前位置: 移动技术网 > IT编程>开发语言>c# > WinForm自定义函数FindControl实现按名称查找控件

WinForm自定义函数FindControl实现按名称查找控件

2019年07月18日  | 移动技术网IT编程  | 我要评论

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

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网