/* 作者:耿奕廷 版權(quán)所有,轉(zhuǎn)載時(shí)請(qǐng)注明出處及作者 */
假設(shè)我要遍歷所有的Label控件.我們知道一個(gè)窗體中的所有控件都是Form.Controls中的成員,想要得到窗體中的所以成員,可以用foreach來(lái)遍歷Controls屬性中的對(duì)象。注意,Controls屬性中包含的對(duì)象都是以Control基類形式存在的,這就是說(shuō)我們只能用foreach(Control temp inthis.Controls)來(lái)遍歷。對(duì)于任何一個(gè)由Control派生來(lái)的類,或者說(shuō)是所以控件,可以用其GetType()函數(shù)來(lái)得到控件的類型。如果要判判斷具體類型需要將類型轉(zhuǎn)為字符串:tempControl.GetType().ToString() 它得到的是一個(gè)控件的完整名字,如:System.Windows.Forms.Label。
現(xiàn)在我們考慮另一種情況,在控件中,有一些控件有子控件如 Panel ,GroupBox,而這些控件中又可能包含其它的Panel,GroupBox,所以我們必須判斷出這些“母控件”,并用遞歸方法對(duì)其中的控件遍歷!
代碼如下,在窗體中至少有一個(gè)LISTBOX和 一個(gè)按鈕,注意每個(gè)函數(shù)接受的參數(shù)類型。
private void GetLabeinP(Panel temp) //對(duì)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) //對(duì)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;
}
}
}
聯(lián)系客服