Reputation: 2948
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();
Upvotes: 4
Views: 23424
Reputation: 31
We can do this on the front end in C#
@Html.DropDownList("sample",new SelectList(DropDownList1, "DataTextField", "DataValueField "), "Select")
Upvotes: 0
Reputation: 1841
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.
Upvotes: 7
Reputation: 325
You can do it with this way:
dropdownlist1.Items.Insert(0, new ListItem("Select here...", string.Empty));
Upvotes: 1
Reputation: 1632
You can do it in SQL:
sql = @"Select Nome From DanielPessoas UNION ALL Select '' Order by Nome";
Upvotes: 0
Reputation: 1399
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"));
Upvotes: 1
Reputation: 32233
After your DataBind call, add this code.
DropDownList1.Items.Insert(0, new ListItem(string.Empty, string.Empty));
Upvotes: 14