问题
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?
回答1:
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.
回答2:
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.
回答3:
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.
来源:https://stackoverflow.com/questions/251985/databinding-dropdown-control-in-net