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

前端 未结 3 677
鱼传尺愫
鱼传尺愫 2021-01-05 02:57

If I use a DropDownList:

 

        
相关标签:
3条回答
  • 2021-01-05 03:32

    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"));
    
    0 讨论(0)
  • 2021-01-05 03:39
    <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();
    
    0 讨论(0)
  • 2021-01-05 03:40

    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.

    0 讨论(0)
提交回复
热议问题