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;
ddList1.DataBind();
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>
</select>
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.
If you are building ListItems, you have no need to use DataBind() in the first place.
Just add them to your DropDownList:
DataBind() is useful when you already have a collection/dataobject (usually a DataTable or DataView) that can be used as a DataSource, by setting the DataTextField and DataValueField (as buyutec wrote).
"If you are building ListItems, you have no need to use DataBind() in the first place."
Adding directly to the dropdownlist is the easy way (and given the example code the right one) but lets say you have an unordered datasource and you want the list items sorted.
One way of achieving this would be to create a generic list of ListItem and then use the inherited sort method before databinding to the list.
There are many wys to skin a cat...
And here is the method that performs the data binding. You can exactly see what is going on:
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.