views:

731

answers:

3

I am binding the dropdown with db entity.

ddlCustomer.DataSource = Customer.GetAll();
ddlCustomer.DataTextField = "CustomerName";
ddlCustomer.DataBind();

I want to add "SELECT" as the first itemlist in dropdown and bind then entity to the dropdown. How can i do this?

A: 

I don't know if there is a one line solution to this, but what i was doing before is, not using DataBind , and first create the ListItem object that will have "Select" as the text, then loop through the collection returned from Customer.GetAll() and create a ListItem object for each item in the collection and add it to the drop down list using "DropDownList.Iems.Add(MyItem)" , i know it doesn't look very brilliant but it does the job , after all this is what DataBind is doing in behind.

Mohamed Faramawi
+4  A: 

Add:

ddlCustomer.Items.Insert(0, "SELECT");

After ddlCustomer.DataBind();

The item must be inserted after the data bind because the data bind clears the items.

Aleris
You can also set the 'AppendDataBoundItems' property of the DropDownList to 'True'. "Gets or sets a value that indicates whether list items are cleared before data binding." from http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.listcontrol.appenddatabounditems.aspx.
David HAust
A: 

I know there is an answer already, but you can also do this:

<asp:DropDownList AppendDataBoundItems="true" ID="ddlCustomer" runat="server">
    <asp:ListItem Value="0" Text="Select"/>
</asp:DropDownList>

That way, you won't have to worry about when you call Databind and when you add the select-item.

Stefan