[英]Looping through controls and using a function
我有很多Panels
, Labels
和PictureBox
,並且我有一個像我這樣使用的函數myFunction(panel1,label2,pictureBox3);
我只需要用這行代碼寫大約40行...
我想知道是否有一種方法可以使功能循環遍歷我需要的所有元素……類似... while(i==40){myFunction(panel[i],label[i],pictureBox[i]); i++;}
while(i==40){myFunction(panel[i],label[i],pictureBox[i]); i++;}
這個怎么樣:
for (i = 0; i < 40; i++)
{
var panel = this.Controls
.OfType<Panel>()
.First(p => p.Name == string.Format("panel{0}"))
var label = this.Controls
.OfType<Label>()
.First(p => p.Name == string.Format("label{0}"));
var panel = this.Controls
.OfType<PictureBox>()
.First(p => p.Name == string.Format("pictureBox{0}"));
myFunction(panel, label, pictureBox);
}
您可以遍歷表單和容器控件的Controls
集合。 但是,您將遇到的問題是如何正確地將一個與另一個關聯。 如果它們始終處於這三個組中,那么遍歷所有控件似乎沒有辦法確定每個控件所屬的直觀組。
即使這樣做,這也不是我想要依靠的東西。
相反,您可以在表單級別跟蹤此“分組”。 它可能像自定義對象一樣簡單,例如:
class PanelPictureGroup
{
public Panel GroupPanel { get; set; }
public Label GroupLabel { get; set; }
public PictureBox GroupPictureBox { get; set; }
}
該對象本身不執行任何操作,但是您可以在加載表單時初始化它們的集合。 就像是:
private List<PanelPictureGroup> myGroups = new List<PanelPictureGroup>();
並在加載事件中,或在以下形式的地方:
myGroups.Add(new PanelPictureGroup { GroupPanel = panel1, GroupLabel = label2, GroupPictureBox = pictureBox3 });
myGroups.Add(new PanelPictureGroup { GroupPanel = panel4, GroupLabel = label5, GroupPictureBox = pictureBox6 });
// and so on, probably abstracted into a form initialization method and called once on form load
在這一點上,所有控件實際上都在邏輯組中,因此被明確設置。 (而不是嘗試根據完全“任意”的控件“數字”的假設來推斷組。)現在遍歷它們很簡單:
foreach (var myGroup in myGroups)
myFunction(myGroup.GroupPanel, myGroup.GroupLabel, myGroup.GroupPictureBox);
可以封裝到對象中的邏輯越多越好。 正如埃里克·雷蒙德(Eric Raymond)曾經說過的那樣:“智能數據結構和啞代碼比其他方法要好得多。”
可以使用Controls.Find()和如下代碼根據其名稱檢索所有這些控件:
Panel pnl;
Label lbl;
PictureBox pb;
Control[] matches;
for(int i = 1; i <= 40; i = i + 3)
{
matches = this.Controls.Find("panel" + i.ToString(), true);
if (matches.Length > 0 && matches[0] is Panel)
{
pnl = matches[0] as Panel;
matches = this.Controls.Find("label" + (i + 1).ToString(), true);
if (matches.Length > 0 && matches[0] is Label)
{
lbl = matches[0] as Label;
matches = this.Controls.Find("pictureBox" + (i + 2).ToString(), true);
if (matches.Length > 0 && matches[0] is PictureBox)
{
pb = matches[0] as PictureBox;
myFunction(pnl, lbl, pb);
}
}
}
}
您可以在Form的Load()事件中使用類似這樣的代碼來填充David提出的組,這是一個好主意。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.