C#实现根据指定容器和控件名字获得控件的方法_技术学院_宜昌市隼壹珍商贸有限公司

您好,欢迎访问宜昌市隼壹珍商贸有限公司

400 890 5375
当前位置: 主页 > 新闻动态 > 技术学院

C#实现根据指定容器和控件名字获得控件的方法

发布时间:2026-01-18  |  点击率:

本文所述为C#实现根据指定容器和控件名字获得控件的方法,在进行C#应用程序设计时有一定的借鉴价值。分享给大家供大家参考借鉴。具体实现方法如下:

功能代码如下:

/// <summary>
/// 根据指定容器和控件名字,获得控件
/// </summary>
/// <param name="obj">容器</param>
/// <param name="strControlName">控件名字</param>
/// <returns>控件</returns>
private object GetControlInstance(object obj,string strControlName)
{
 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;//控件不存在
}

示例如下:

((Button) GetControlInstance(this,"button7")).BackColor = Color.Red;
((Button) GetControlInstance(this.groupBox4,"button7")).PerformClick();

希望本文所述实例对大家C#程序设计有所帮助。

全国统一服务电话

400 890 5375

电子邮箱:879577@qq.com

公司地址:宜昌市西陵区黄河路5号三峡明珠10栋1051室

咨询微信

TEL:13680874598