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

1

7

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?

Disremember answered 21/3, 2012 at 15:2 Comment(1)
ahhh, damn... see it now, but you've seen it yourself too :-)Commitment
S
11

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.

Sollars answered 21/3, 2012 at 15:6 Comment(5)
Thanks, but the answer was even simpler - I'd forgotten to specify the DataTextField and DataValueFieldDisremember
What do you mean by "you're not supposed to bind ListItems"? You can bind to anything I think.Disremember
You can do it, but using the first approach I described would be the natural way to go since Items collection is a collection of ListItem.Sollars
Fair point - I've changed the code :) I guess I'm just too used to databinding. Probably no real advantage/disadvantage of either method over the other though.Disremember
Important point that it is not possible to just Add items directly into the DropDownList. You have to use DataSource.Tedmund

© 2022 - 2024 — McMap. All rights reserved.