加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 04:03:45 所属栏目:百科 来源:网络整理
导读:本文所述实例实现WinForm自定义函数FindControl实现按名称查找控件的功能,在C#程序开发中有一定的实用价值。供大家参考研究。 关键代码如下: /// summary/// 按名称查找控件/// /summary/// param name="parentControl"查找控件的父容器控件/param//

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读