2012-06-11 44 views
3

我有一個表需要27個單元格中的27個下拉菜單來接受用戶輸入。目前我宣佈他們所有的27個像這樣:C#聲明同一表的多個實例

DropDownList DropList1 = new DropDownList(); 
DropList1.ID = "TrendList1"; 
DropList1.AutoPostBack = true; 
DropList1.SelectedIndexChanged += new EventHandler(this.Selection_Change); 
DropList1.DataSource = CreateDataSource(); 
DropList1.DataTextField = "ColorTextField"; 
DropList1.DataValueField = "ColorValueField"; 
DropList1.DataBind(); 

DropDownList DropList2 = new DropDownList(); 
DropList2.ID = "TrendList2"; 
DropList2.AutoPostBack = true; 
DropList2.SelectedIndexChanged += new EventHandler(this.Selection_Change); 
DropList2.DataSource = CreateDataSource(); 
DropList2.DataTextField = "ColorTextField"; 
DropList2.DataValueField = "ColorValueField"; 
DropList2.DataBind(); 

etc... 

但是我知道必須有比我寫的暴力代碼更好的方法。不幸的是,我是網絡編程的新手,我一直無法找到一個更好的方法來做到這一點。

任何意見表示讚賞。

問候。

回答

2
var data = CreateDataSource(); 

for(x = 1; x < 28; x++) 
{ 
    DropDownList dl = new DropDownList(); 
    dl.ID = "TrendList" + x.ToString(); 
    dl.AutoPostBack = true; 
    dl.SelectedIndexChanged += new EventHandler(this.Selection_Change); 
    dl.DataSource = data; 
    dl.DataTextField = "ColorTextField"; 
    dl.DataValueField = "ColorValueField"; 
    dl.DataBind(); 
    // add it to the cell here too 
} 
+0

這假設'CreateDataSource()'是確定性的(每次調用時都會返回相同的結果),但否則它肯定是合適的解決方案。如果'CreateDataSource()'做了一些不明顯的事情,比如每次調用一個新的數據源並遞增一個計數器,或者其他任何東西,你都會希望將它保留在循環體中。 (鑑於描述,我不認爲是這種情況,但兩者都不明確。) –

+0

謝謝。我也應該問如何自動化這些: 'if(!IsPostBack) { DropList1.SelectedIndex = 0; etc ... }' and 'p1.Controls.Add(DropList1); p2.Controls.Add(DropList2); etc ...' DropList2.SelectedIndex = 0; – Kevin

+0

沒關係。我只是想出了它。謝謝你的幫助。 – Kevin