C#声明同一个表的多个实例

时间:2012-06-11 17:25:21

标签: c# asp.net

我有一个表需要27个单元格中的27个下拉菜单才能接受用户输入。目前我宣布所有27个人都这样:

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...

但是我知道必须有比我写的强力代码更好的方法。不幸的是,我是网络编程的新手,我还没有找到更好的方法来做到这一点。

感谢任何建议。

问候。

1 个答案:

答案 0 :(得分: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
}