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

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

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

如有任何建议,我们将不胜感激。

问候。

最佳答案

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
}

关于C# 声明同一个表的多个实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10984737/

相关文章:

asp.net - 在页面加载时使用 JavaScript 填充文本框

asp.net - Web.config - 自定义错误页面不起作用

c# - TFS 构建失败。对源代码管理中的文件的未解决引用

ASP.NET:Server.Execute() 中的 BOM

c# - 从 C# 以编程方式将文件创建到 Onedrive?

c# - Decimal 类型从 In-memory Sqlite 数据库中读取为 double 或 int

c# - HttpPostedFileBase to byte[]如何保持编码?

javascript - 从C#代码调用js文件中的函数

c# - 从 PDF 中删除文本

c# - 如何获取具有多个参数的查询字符串