First Item on Dropdownlist in blank

21,429

Solution 1

After your DataBind call, add this code.

DropDownList1.Items.Insert(0, new ListItem(string.Empty, string.Empty));

Solution 2

You can define the empty item in aspx file if you set AppendDataBoundItems property to true.

<asp:DropDownList ID="ddlPersons" runat="server" AppendDataBoundItems="true" DataValueField="ID" DataTextField="Name">
    <asp:ListItem> -- please select person -- </asp:ListItem>
</asp:DropDownList>

Then you can databind items from the database in the codebehind:

ddlPersons.DataSource = personsList;
ddlPersons.DataBind();

I regard this "empty item" as presentation / UI, so I like to put it in the aspx. It also keeps the codebehind simpler.

Solution 3

Do something like this: Here is a simple example

<asp:DropDownList ID="ddlFruits" runat="server">

        <asp:ListItem Value="1" Text="Oranges"></asp:ListItem>
        <asp:ListItem Value="2" Text="Apples"></asp:ListItem>
        <asp:ListItem Value="3" Text="Grapes"></asp:ListItem>
        <asp:ListItem Value="4" Text="Mangoes"></asp:ListItem>
    </asp:DropDownList>

And in the code behind

ddlFruits.Items.Insert(0, new ListItem(string.Empty, "0"));

Solution 4

You can do it with this way:

dropdownlist1.Items.Insert(0, new ListItem("Select here...", string.Empty));
Share:
21,429
Daniel
Author by

Daniel

Updated on June 21, 2020

Comments

  • Daniel
    Daniel almost 4 years

    How to put the first item on the DropDownList in blank ? In VB is something like, DropDownList.index[0] = ""; I did this:

    string StrConn = ConfigurationManager.ConnectionStrings["connSql"].ConnectionString;
        SqlConnection conn = new SqlConnection(StrConn);
    
        conn.Open();
    
        SqlDataReader dr;
    
        string sql;
        sql = @"Select Nome From DanielPessoas";
    
        SqlCommand cmd = new SqlCommand(sql, conn);
        dr = cmd.ExecuteReader();
    
        DropDownList1.DataSource = dr;
        DropDownList1.DataTextField = "Nome";
        DropDownList1.DataValueField = "Nome";
        DropDownList1.DataBind();