Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 294
NickG Avatar asked Mar 21 '12 15:03

NickG


1 Answers

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.

like image 50
Claudio Redi Avatar answered Sep 19 '22 07:09

Claudio Redi