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

本文关键字:实例 声明 | 更新日期: 2023-09-27 18:36:59

我有一个表格,需要 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...

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

任何建议不胜感激。

问候。

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

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
}