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

C#声明同一表的多个实例,c#,asp.net,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 =

我有一个表格,需要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...
但是我知道一定有比我写的暴力代码更好的方法。不幸的是,我对网络编程还不熟悉,还没有找到更好的方法

任何建议都将不胜感激

关于。

var data=CreateDataSource();
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
}
对于(x=1;x<28;x++) { DropDownList dl=新的DropDownList(); dl.ID=“趋势列表”+x.ToString(); dl.AutoPostBack=true; dl.SelectedIndexChanged+=新事件处理程序(此.Selection\u更改); dl.DataSource=数据; dl.DataTextField=“ColorTextField”; dl.DataValueField=“ColorValueField”; dl.DataBind(); //也将其添加到此处的单元格中 }
这假设
CreateDataSource()
是确定性的(每次调用它时都会返回相同的内容),但除此之外,它肯定是正确的解决方案。如果
CreateDataSource()
执行了一些不明显的操作,例如每次调用一个新的数据源时返回该数据源,并递增一个计数器,或者诸如此类的操作,则希望将其保留在循环体中。(根据描述,我认为情况并非如此,但两种情况都不清楚。)谢谢。我还应该问一下如何自动执行这些操作:
if(!IsPostBack){DropList1.SelectedIndex=0;等等。}
p1.Controls.Add(DropList1);p2.控件。添加(滴流器2);等等。
DropList2.SelectedIndex=0;没有足够的信息来确定每个DropDownList的数据源是否相同所有DropDownList的数据源都相同。我想用DropDownList实例化表中的占位符,但这段代码(添加到上面的代码中)引发运行时错误:
PlaceHolder ph=(占位符)form1.FindControl(“p”+x.ToString());ph.对照品添加(dl)我应该补充占位符具有顺序ID:p1、p2、…、p27。