本文所述為C#實(shí)現(xiàn)根據(jù)指定容器和控件名字獲得控件的方法,在進(jìn)行C#應(yīng)用程序設(shè)計(jì)時(shí)有一定的借鑒價(jià)值。分享給大家供大家參考借鑒。具體實(shí)現(xiàn)方法如下:
功能代碼如下:
/// <summary>/// 根據(jù)指定容器和控件名字,獲得控件/// </summary>/// <param name="obj">容器</param>/// <param name="strControlName">控件名字</param>/// <returns>控件</returns>private object GetControlInstance(object obj,string strControlName){ IEnumerator Controls = null;//所有控件 Control c = null;//當(dāng)前控件 Object cResult=null;//查找結(jié)果 if(obj.GetType() == this.GetType())//窗體 { Controls = this.Controls.GetEnumerator(); } else//控件 { Controls = ((Control)obj).Controls.GetEnumerator(); } while(Controls.MoveNext())//遍歷操作 { c = (Control)Controls.Current;//當(dāng)前控件 if(c.HasChildren)//當(dāng)前控件是個(gè)容器 { cResult = GetControlInstance(c,strControlName);//遞歸查找 if(cResult==null)//當(dāng)前容器中沒(méi)有,跳出,繼續(xù)查找 continue; else//找到控件,返回 return cResult; } else if(c.Name == strControlName)//不是容器,同時(shí)找到控件,返回 { return c; } } return null;//控件不存在}示例如下:
((Button) GetControlInstance(this,"button7")).BackColor = Color.Red;((Button) GetControlInstance(this.groupBox4,"button7")).PerformClick();
希望本文所述實(shí)例對(duì)大家C#程序設(shè)計(jì)有所幫助。
新聞熱點(diǎn)
疑難解答
圖片精選