110,561
社区成员
发帖
与我相关
我的任务
分享
/// <summary>
/// 根据指定容器和控件名字,获得控件
/// </summary>
/// <param name="obj">容器</param>
/// <param name="strControlName">控件名字</param>
/// <returns></returns>
private object GetControlInstance(object obj,string strControlName)
{
System.Collections.IEnumerator _Controls = null; //所有控件
Control c = null; //当前控件
object cResult = null; //查找结果
if (obj.GetType() == this.GetType()) //窗体
_Controls = this.Controls.GetEnumerator();
else
//控件
_Controls = ((Control)obj).Controls.GetEnumerator();
//遍历操作
while (_Controls.MoveNext())
{
//当前控件
c = (Control)_Controls.Current;
if (c.HasChildren) //当前控件是个容器
{
cResult = GetControlInstance(c, strControlName); //递归查找
if (cResult == null) //当前容器中没有,跳出,继续查找
continue;
else
//找到控件,返回
return cResult;
}
else if (c.Name == strControlName)
//不是容器,同时找到控件,返回
return c;
}
return null;
}
调用方法 For Example:
((Button)GetControlInstance(this, "button7")).BackColor = Color.Red;
((Button)GetControlInstance(this.groupBox1, "button1")).PerformClick();