How to add a default “Select” option to this ASP.NET DropDownList control?

后端 未结 7 2086
别那么骄傲
别那么骄傲 2021-01-02 05:06

I am a new ASP.NET developer and I am trying to learn Linq-To-Entities. I am trying to bind a DropDownList with the Linq statement for retrieving the list of status in the S

相关标签:
7条回答
  • 2021-01-02 05:19

    The reason it is not working is because you are adding an item to the list and then overriding the whole list with a new DataSource which will clear and re-populate your list, losing the first manually added item.

    So, you need to do this in reverse like this:

    Status status = new Status();
    DropDownList1.DataSource = status.getData();
    DropDownList1.DataValueField = "ID";
    DropDownList1.DataTextField = "Description";
    DropDownList1.DataBind();
    
    // Then add your first item
    DropDownList1.Items.Insert(0, "Select");
    
    0 讨论(0)
  • 2021-01-02 05:19

    I have tried with following code. it's working for me fine

    ManageOrder Order = new ManageOrder();
    Organization.DataSource = Order.getAllOrganization(Session["userID"].ToString());
    Organization.DataValueField = "OrganisationID";
    Organization.DataTextField = "OrganisationName";                
    Organization.DataBind();                
    Organization.Items.Insert(0, new ListItem("Select Organisation", "0"));
    
    0 讨论(0)
  • 2021-01-02 05:20

    Although it is quite an old question, another approach is to change AppendDataBoundItems property. So the code will be:

    <asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True"
                      OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged"
                      AppendDataBoundItems="True">
         <asp:ListItem Selected="True" Value="0" Text="Select"></asp:ListItem>
    </asp:DropDownList>
    
    0 讨论(0)
  • 2021-01-02 05:20

    If you do an "Add" it will add it to the bottom of the list. You need to do an "Insert" if you want the item added to the top of the list.

    0 讨论(0)
  • 2021-01-02 05:23
    Private Sub YourWebPage_PreRenderComplete(sender As Object, e As EventArgs) Handles Me.PreRenderComplete
    
         If Not IsPostBack Then
         DropDownList1.Items.Insert(0, "Select")
         End If
    
    End Sub
    
    0 讨论(0)
  • 2021-01-02 05:30

    Move DropDownList1.Items.Add(new ListItem("Select", "0", true)); After bindStatusDropDownList();

    so:

        if (!IsPostBack)
        {
            bindStatusDropDownList(); //first create structure
            DropDownList1.Items.Add(new ListItem("Select", "0", true)); // after add item
        }
    
    0 讨论(0)
提交回复
热议问题