c# - 如何将列表项添加到在代码隐藏中生成的下拉列表?

我在后面的代码中动态创建下拉菜单。我想添加一个列表项,它是下拉列表的默认选择。

int Persons= int.Parse(TextBox_persons.Text) + 1;

for (int i = 1; i < Persons; i++)
{
     DropDownList DropDownList_menuchoice = new DropDownList();
     DropDownList_menuchoice.DataSource = Menu.GetAllMenus();
     DropDownList_menuchoice.CssClass = "form-control";
     DropDownList_menuchoice.Items.Add(new ListItem("please select a menu", "-1"));
     DropDownList_menuchoice.DataTextField = "titel";
     DropDownList_menuchoice.DataValueField = "titel";
     DropDownList_menuchoice.DataBind();
     Panel1.Controls.Add(DropDownList_menuchoice);
}

为什么这行不通?我一直在网上寻找答案,但每个人都建议使用 items.add 代码,但它对我不起作用。它只显示我从数据库中检索的数据,而不是我在上面的代码中添加的列表项。

如果你知道这是为什么,请帮助我。

最佳答案

首先,您需要在调用 DataBind 方法后添加项目。 像这样:

DropDownList DropDownList_menuchoice = new DropDownList();
DropDownList_menuchoice.DataSource = Menu.GetAllMenus();
DropDownList_menuchoice.CssClass = "form-control";
DropDownList_menuchoice.DataTextField = "titel";
DropDownList_menuchoice.DataValueField = "titel";
DropDownList_menuchoice.DataBind();
DropDownList_menuchoice.Items.Add(new ListItem("please select a menu", "-1"));

然后你需要使用 Insert 方法将它添加到索引 0(作为第一项):

DropDownList_menuchoice.Items.Insert(0, new ListItem("please select a menu", "-1"));

您也可以先将项目添加到数据中,然后再设置数据源属性。像这样:

var data = Menu.GetAllMenus();
data.Insert(0, new Menu { titel = "please select a menu" });
DropDownList_menuchoice.DataSource = data;
...

https://stackoverflow.com/questions/23968555/

相关文章:

bash - 如何确定哪些主机名未解析为 IP 地址?

netlogo - 如何在Netlogo中直接保存.txt文件的数据?

image - 我需要缩小图像尺寸?有人可以帮助我吗?

php - 如何通过表格中的表单发送复选框状态

sql - 自增问题postgresql

arm - 使用 llvm 从桌面交叉编译到 arm

r - 使用 gbm() 分类 - 错误

php - 如何为 PHP 类提供表单操作

dynamic - 在 MongoDB 中为动态添加的字段创建索引

hornetq - 在同一个虚拟机中启动多个嵌入式 HornetQ 代理