First item in dropdown in space

How to transfer the first item in DropDownList to empty? VB has something like: DropDownList.index [0] = ""; I have done 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(); 
+4
source share
6 answers

After calling DataBind, add this code.

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

You can define an empty element in an aspx file if the AppendDataBoundItems property AppendDataBoundItems set 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 import the database items from the database in code:

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

I view this "empty element" as a view / user interface, so I like to put it in aspx. It also simplifies code coding.

+7
source

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 code

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

You can do it as follows:

 dropdownlist1.Items.Insert(0, new ListItem("Select here...", string.Empty)); 
+1
source

You can do this in SQL:

 sql = @"Select Nome From DanielPessoas UNION ALL Select '' Order by Nome"; 
0
source

We can do it at the front end in C #

@ Html.DropDownList ("sample", new SelectList (DropDownList1, "DataTextField", "DataValueField"), "Select")

0
source

All Articles