Adding ListItems to a DropDownList from a generic list


I have a this aspx-code: (sample)

<asp:DropDownList runat="server" ID="ddList1"></asp:DropDownList>   

With this codebehind:

List<System.Web.UI.WebControls.ListItem> colors = new List<System.Web.UI.WebControls.ListItem>();
colors.Add(new ListItem("Select Value", "0"));
colors.Add(new ListItem("Red", "1"));
colors.Add(new ListItem("Green", "2"));
colors.Add(new ListItem("Blue", "3"));
ddList1.DataSource = colors;

The output looks like this:

<select name="ddList1" id="ddList1">
    <option value="Select Value">Select Value</option>
    <option value="Red">Red</option>
    <option value="Green">Green</option>
    <option value="Blue">Blue</option>

My question is: Why did my values (numbers) disappear and the text used as the value AND the text? I know that it works if I use the ddList1.Items.Add(New ListItem("text", "value")) method, but I need to use a generic list as the datasource for other reasons.

Best Solution

Because DataBind method binds values only if DataValueField property is set. If you set DataValueField property to "Value" before calling DataBind, your values will appear on the markup.

UPDATE: You will also need to set DataTextField property to "Text". It is because data binding and adding items manually do not work in the same way. Databinding does not know the existence of type ListItem and generates markup by evaluating the items in the data source.