如何将初始"select"值添加到DropDownList

Joh*_*ohn 7 asp.net drop-down-menu

如果我使用DropDownList:

 <asp:DropDownList ID="DropDownListSubContractors" runat="server" 
     DataTextField="Company_Name" DataValueField="id">
 </asp:DropDownList>
Run Code Online (Sandbox Code Playgroud)

我使用/设置的属性允许我在下拉列表中使用'--- Select ---'作为初始选项,而不是列表中的第一个值.

nrs*_*rma 14

您可以使用

<asp:DropDownList ID="DropDownListSubContractors" runat="server" AppendDataBoundItems="true" DataTextField="Company_Name" DataValueField="id">
    <asp:ListItem Text="---Select---" Value="0" />   
</asp:DropDownList>
Run Code Online (Sandbox Code Playgroud)

或者你可以像这样在代码后面动态添加它

DropDownListSubContractors.Items.Add(new ListItem("---Select---", "0"));
Run Code Online (Sandbox Code Playgroud)


Dar*_*rov 7

<asp:DropDownList ID="DropDownListSubContractors" runat="server" AppendDataBoundItems="true" DataTextField="Company_Name" DataValueField="id">
    <asp:ListItem Text="---Select---" Value="" />   
</asp:DropDownList>
Run Code Online (Sandbox Code Playgroud)

您现在可以像往常一样将DropDown绑定到数据源中,并且此数据源不需要包含默认值项:

IEnumerable<MyViewModel> model = ...
DropDownListSubContractors.DataSource = model;
DropDownListSubContractors.DataBind();
Run Code Online (Sandbox Code Playgroud)