How do you programmatically add ListItems to DropDownList in ASP.NET?

NickG picture NickG · Mar 21, 2012 · Viewed 18.8k times · Source

I'm trying to add items to a dropdown list using a List of ListItems, but it's not picking up the value (only the text).

The code is below (simplified from the code I'm actually using):

    PositionDropDown.DataSource = GetPositionOptions();
    PositionDropDown.DataBind();


    private List<ListItem> GetPositionOptions() 
    {
        List<ListItem> items = new List<ListItem>();
        items.Add(new ListItem("",""));
        items.Add(new ListItem("Top (main)", "TOP"));
        items.Add(new ListItem("Bottom (full width)", "BTM"));
        items.Add(new ListItem("Bottom Left", "MIL"));
        items.Add(new ListItem("Bottom Middle", "MID"));
        return items;
    }

However the rendered HTML is missing the values specified in the 2nd parameter of the ListItem constructor:

<option value=""></option>
<option value="Top (main)">Top (main)</option>
<option value="Bottom (full width)">Bottom (full width)</option>
<option value="Bottom Left">Bottom Left</option>
<option value="Bottom Middle">Bottom Middle</option>

Why is it not using the specified "value" and instead just repeating the "name" when rendering the HTML? What am I doing wrong?

Answer

Claudio Redi picture Claudio Redi · Mar 21, 2012

Try with this code. You're mixing manually item addition with data binding.

private void SetPositionOptions() 
{
    PositionDropDown.Items.Add(new ListItem("",""));
    PositionDropDown.Items.Add(new ListItem("Top (main)", "TOP"));
    PositionDropDown.Items.Add(new ListItem("Bottom (full width)", "BTM"));
    PositionDropDown.Items.Add(new ListItem("Bottom Left", "MIL"));
    PositionDropDown.Items.Add(new ListItem("Bottom Middle", "MID"));
}

I'd say that if you want to keep your code as it is you should add this 2 lines

PositionDropDown.DataSource = GetPositionOptions();
PositionDropDown.DataTextField = "Text";
PositionDropDown.DataValueField = "Value";
PositionDropDown.DataBind();

But it make no sense, you're not supposed to bind ListItems.