WinForm自定义函数FindControl实现按名称查找控件
更新时间:2014年08月19日 17:25:29 投稿:shichen2014
这篇文章主要介绍了WinForm自定义函数FindControl实现按名称查找控件,需要的朋友可以参考下
本文所述实例实现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#学习能有所帮助!
相关文章
C# CultureInfo之常用InvariantCulture案例详解
这篇文章主要介绍了C# CultureInfo之常用InvariantCulture案例详解,本篇文章通过简要的案例,讲解了该项技术的了解与使用,以下就是详细内容,需要的朋友可以参考下2021-08-08
asp.net core 使用 tensorflowjs实现 face recognition的源代码
tensorflowjs,在该项目中使用了ml5js这个封装过的机器学习JavaScript类库, 使用起来更简单,本文给大家分享asp.net core 使用 tensorflowjs实现 face recognition的源代码,需要的朋友参考下吧2021-06-06


最新评论