roy-willemse
roy-willemse

Reputation: 324

How to add a listitem to a dropdownlist that is generated in code behind?

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.

Upvotes: 3

Views: 14001

Answers (2)

yusefnejad
yusefnejad

Reputation: 176

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;
...

Upvotes: 3

शेखर
शेखर

Reputation: 17614

You need to recreate you dropdown on pre_init event.

protected override void OnPreInit(EventArgs e)
{
    base.OnPreInit(e);
    //create your dropdown here
}

Edit -1

int Persons= int.Parse(TextBox_persons.Text) + 1;
Session["Persons"]=Person;

on pre_init

protected override void OnPreInit(EventArgs e)
{
    int Persons=0;
    if(Session["Persons"]!=null)
    Persons= int.Parse(Session["Persons"].ToString()) + 1;
    for (int i = 1; i < Persons; i++)
    {
        DropDownList DropDownList_menuchoice = new DropDownList();
        DropDownList_menuchoice.DataTextField = "titel";
        Panel1.Controls.Add(DropDownList_menuchoice);
     }
    base.OnPreInit(e);
}

Upvotes: 0

Related Questions