1

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?

Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
jbcedge
  • 18,965
  • 28
  • 68
  • 89

3 Answers3

4

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
  • 7,981
  • 3
  • 36
  • 42
  • 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. – Dhaust Oct 30 '08 at 22:41
0

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
  • 641
  • 5
  • 13
0

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
  • 1,719
  • 2
  • 15
  • 27