数据绑定下拉列表,包含数据表并添加自定义值

时间:2013-07-22 09:16:22

标签: c# asp.net

我正在使用数据表对我的下拉列表进行数据绑定。我需要在下拉列表中添加一个项目,这需要是选择中的第一项。我尝试了很多方法但没有任何工作。

ddlCountry.Items.Add("--Select--");
ddlCountry.DataTextField = "Country";
ddlCountry.DataValueField = "Country";
ddlCountry.DataSource = dt;
ddlCountry.DataBind();

3 个答案:

答案 0 :(得分:3)

您的页面声明:

<asp:dropdownlist id="ddlCountry" AppendDataBoundItems="true" runat="server" >
    <asp:ListItem Value="0" Text="[ Select ]" Selected="True"></asp:ListItem>
</asp:dropdownlist>

AppendDataBoundItems="true" is the key.

您的代码背后:

ddlCountry.DataTextField = "Country";
ddlCountry.DataValueField = "Country";
ddlCountry.DataSource = dt;
ddlCountry.DataBind();

答案 1 :(得分:3)

试试这个

 ddlCountry.DataTextField = "Country";
 ddlCountry.DataValueField = "Country";
 ddlCountry.DataSource = dt;
 ddlCountry.DataBind();
 ddlCountry.Items.Insert(0, new ListItem("Select Country", "0"));

答案 2 :(得分:2)

在添加

之前先绑定数据
ddlCountry.DataTextField = "Country";
ddlCountry.DataValueField = "Country";
ddlCountry.DataSource = dt;
ddlCountry.DataBind();
ddlCountry.Items.Add("--Select--");