WinForm实现按名称递归查找控件的方法
本文所述实例主要实现了WinForm实现按名称递归查找控件的功能,在C#项目开发中有一定的应用价值,分享给大家供大家参考借鉴。
关键代码如下:
///<summary>
///向下递归查找控件
///</summary>
///<paramname="parentControl">查找控件的父容器控件</param>
///<paramname="findCtrlName">查找控件名称</param>
///<returns>若没有查找到返回NULL</returns>
publicstaticControlDownRecursiveFindControl(thisControlparentControl,stringfindCtrlName)
{
Control_findedControl=null;
if(!string.IsNullOrEmpty(findCtrlName)&&parentControl!=null)
{
foreach(ControlctrlinparentControl.Controls)
{
if(ctrl.Name.Equals(findCtrlName))
{
_findedControl=ctrl;
break;
}
else
{
if(ctrl.Controls.Count>0)
_findedControl=DownRecursiveFindControl(ctrl,findCtrlName);
}
}
}
return_findedControl;
}
///<summary>
///将Control转换某种控件类型
///</summary>
///<typeparamname="T">控件类型</typeparam>
///<paramname="control">Control</param>
///<paramname="result">转换结果</param>
///<returns>若成功则返回控件;若失败则返回NULL</returns>
publicstaticTCast<T>(thisControlcontrol,outboolresult)whereT:Control
{
result=false;
T_castCtrl=null;
if(control!=null)
{
if(controlisT)
{
try
{
_castCtrl=controlasT;
result=true;
}
catch(Exceptionex)
{
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("NotFinded.");
}
希望本文所述实例能够对大家的C#程序设计有所帮助!