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();
After your DataBind call, add this code.
DropDownList1.Items.Insert(0, new ListItem(string.Empty, string.Empty));
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With