How to add an initial “select” value to a DropDown

2019-02-13 09:08发布

问题:

If I use a DropDownList:

 <asp:DropDownList ID="DropDownListSubContractors" runat="server" 
     DataTextField="Company_Name" DataValueField="id">
 </asp:DropDownList>

What attribute do I use/set that allows me to use '---Select---' as initial option on the drop down, instead of the first value in the list.

回答1:

You can use

<asp:DropDownList ID="DropDownListSubContractors" runat="server" AppendDataBoundItems="true" DataTextField="Company_Name" DataValueField="id">
    <asp:ListItem Text="---Select---" Value="0" />   
</asp:DropDownList>

Or you can add this dynamically at code behind like this

DropDownListSubContractors.Items.Add(new ListItem("---Select---", "0"));


回答2:

<asp:DropDownList ID="DropDownListSubContractors" runat="server" AppendDataBoundItems="true" DataTextField="Company_Name" DataValueField="id">
    <asp:ListItem Text="---Select---" Value="" />   
</asp:DropDownList>

You could now bind your DropDown in the code behind as usual to the datasource and this data source doesn't need to contain a default value item:

IEnumerable<MyViewModel> model = ...
DropDownListSubContractors.DataSource = model;
DropDownListSubContractors.DataBind();


回答3:

You can do this this way:

From Code behind:

DropDownListSubContractors.Items.Insert(0, new ListItem("---Select---", string.Empty));

Note: We use index 0 to make it the first element at the list.