C#完成依據指定容器和控件名字取得控件的辦法。本站提示廣大學習愛好者:(C#完成依據指定容器和控件名字取得控件的辦法)文章只能為提供參考,不一定能成為您想要的結果。以下是C#完成依據指定容器和控件名字取得控件的辦法正文
本文所述為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#法式設計有所贊助。