Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

First Item on Dropdownlist in blank

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(); 
like image 969
Daniel Avatar asked Nov 29 '22 06:11

Daniel


2 Answers

After your DataBind call, add this code.

DropDownList1.Items.Insert(0, new ListItem(string.Empty, string.Empty));
like image 131
SolutionYogi Avatar answered Dec 06 '22 04:12

SolutionYogi


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.

like image 27
Edo Avatar answered Dec 06 '22 03:12

Edo