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

2019-02-13 09:21发布

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.

3条回答
一夜七次
2楼-- · 2019-02-13 09:46
<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楼-- · 2019-02-13 09:58

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.

查看更多
别忘想泡老子
4楼-- · 2019-02-13 10:08

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"));
查看更多
登录 后发表回答