Databinding DropDown Control in .Net

故事扮演 提交于 2019-12-11 08:18:01

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!