8

如果我使用下拉列表:

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

我使用/设置什么属性允许我使用“---Select---”作为下拉菜单中的初始选项,而不是列表中的第一个值。

4

3 回答 3

15

您可以使用

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

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

DropDownListSubContractors.Items.Add(new ListItem("---Select---", "0"));
于 2013-02-04T12:37:17.947 回答
7
<asp:DropDownList ID="DropDownListSubContractors" runat="server" AppendDataBoundItems="true" DataTextField="Company_Name" DataValueField="id">
    <asp:ListItem Text="---Select---" Value="" />   
</asp:DropDownList>

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

IEnumerable<MyViewModel> model = ...
DropDownListSubContractors.DataSource = model;
DropDownListSubContractors.DataBind();
于 2013-02-04T12:34:20.227 回答
2

你可以这样做:

从后面的代码:

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

注意:我们使用索引 0 使其成为列表中的第一个元素。

于 2013-02-04T14:12:37.543 回答