我在后面的代码中动态创建下拉菜单。我想添加一个列表项,它是下拉列表的默认选择。
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/