/* 作者:耿奕廷 版權(quán)所有,轉(zhuǎn)載時請注明出處及作者 */
假
設(shè)我要遍歷所有的Label控件.我們知道一個窗體中的所有控件都是Form.Controls中的成員,想要得到窗體中的所以成員,可以用
foreach來遍歷Controls屬性中的對象。注意,Controls屬性中包含的對象都是以Control基類形式存在的,這就是說我們只能用
foreach(Control temp in
this.Controls)來遍歷。對于任何一個由Control派生來的類,或者說是所以控件,可以用其
GetType()函數(shù)來得到控件的類型。如果要判判斷具體類型需要將類型轉(zhuǎn)為字符串:tempControl.GetType().ToString
() 它得到的是一個控件的完整名字,如:System.Windows.Forms.Label。
現(xiàn)在我們考慮另一種情況,在控件中,有一些控件有子控件如 Panel ,GroupBox,而這些控件中又可能包含其它的Panel,GroupBox,所以我們必須判斷出這些“母控件”,并用遞歸方法對其中的控件遍歷!
代碼如下,在窗體中至少有一個LISTBOX和 一個按鈕,注意每個函數(shù)接受的參數(shù)類型。
private void GetLabeinP(Panel temp) //對panel進(jìn)行遍歷的函數(shù)
{
foreach(Control tempcon in temp.Controls)
{
switch(tempcon.GetType().ToString())
{
case "System.Windows.Forms.Label":
this.listBox1.Items.Add(tempcon.Name);
break;
case "System.Windows.Forms.Panel":
this.GetLabeinP((Panel)tempcon);
break;
case "System.Windows.Forms.GroupBox":
this.GetLabeinG((GroupBox)tempcon);
break;
}
}
}
private void GetLabeinG(GroupBox temp) //對GroupBox遍歷
{
foreach(Control tempcon in temp.Controls)
{
switch(tempcon.GetType().ToString())
{
case "System.Windows.Forms.Label":
this.listBox1.Items.Add(tempcon.Name);
break;
case "System.Windows.Forms.Panel":
this.GetLabeinP((Panel)tempcon);
break;
case "System.Windows.Forms.GroupBox":
this.GetLabeinG((GroupBox)tempcon);
break;
}
}
}
private void button1_Click_1(object sender, System.EventArgs e) //按鈕的代碼
{
this.listBox1.Items.Clear();
foreach(Control tempcon in this.Controls)
{
switch(tempcon.GetType().ToString())
{
case "System.Windows.Forms.Label":
this.listBox1.Items.Add(tempcon.Name);
break;
case "System.Windows.Forms.Panel":
this.GetLabeinP((Panel)tempcon);
break;
case "System.Windows.Forms.GroupBox":
this.GetLabeinG((GroupBox)tempcon);
break;
}
}
}