本文所述為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#程序設計有所幫助。
新聞熱點
疑難解答