How to add a listitem to a dropdownlist that is generated in code behind?
asp.net, c#, drop-down-menu
Solution
first of all u need to add the item After calling the DataBind method. like this:
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"));
then u need to use Insert method to add it at index 0 (as first item):
DropDownList_menuchoice.Items.Insert(0, new ListItem("please select a menu", "-1"));
u can also add the item to the data first, and then set the DataSource property. something like this:
var data = Menu.GetAllMenus();
data.Insert(0, new Menu { titel = "please select a menu" });
DropDownList_menuchoice.DataSource = data;
...
Problem
I dynamically create dropdowns in my code behind. I want to add a listitem that is the default selection of the dropdown. ``` 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); } ``` Why doesn't this work? I've been looking for the answer online however, everyone is suggestion the `items.add` code and it's not working for me. It only shows the data that I retrieve from the database, not the listitem I've added in the code above. Please help me if you know why this is.