views:

798

answers:

5

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();
+7  A: 

After your DataBind call, add this code.

DropDownList1.Items.Insert(0, new ListItem(string.Empty, string.Empty));
SolutionYogi
Beat me to it. The only thing I'd suggest is setting some kind of value to the blank selection so that it will be easier for validation or selected value checking.
Dillie-O
If you use string.empty/"" for the value, then you can use RequiredFieldValidator with it. However, I would recommed putting something into the text field like "Select..."
mgroves
A: 

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"));
Shiva
A: 

You can do it in SQL:

sql = @"Select Nome From DanielPessoas UNION ALL Select '' Order by Nome";
msi77
This is a bad idea, you don't want to change your SQL code to add an empty item for UI purposes.
SolutionYogi
A: 

You can do it with this way:

dropdownlist1.Items.Insert(0, new ListItem("Select here...", string.Empty));
qulzam
A: 

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.

Edo