下拉列表中的第一个项目为空白

Dan*_*iel 4 sql-server asp.net ado.net

如何将DropDownList中的第一项放在空白处?在VB中就像DropDownList.index [0] =""; 我这样做了:

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(); 
Run Code Online (Sandbox Code Playgroud)

Sol*_*ogi 13

在DataBind调用之后,添加此代码.

DropDownList1.Items.Insert(0, new ListItem(string.Empty, string.Empty));
Run Code Online (Sandbox Code Playgroud)


Edo*_*Edo 7

如果将AppendDataBoundItemsproperty 设置为true,则可以在aspx文件中定义空项.

<asp:DropDownList ID="ddlPersons" runat="server" AppendDataBoundItems="true" DataValueField="ID" DataTextField="Name">
    <asp:ListItem> -- please select person -- </asp:ListItem>
</asp:DropDownList>
Run Code Online (Sandbox Code Playgroud)

然后,您可以在代码隐藏中对数据库中的项进行数据绑定:

ddlPersons.DataSource = personsList;
ddlPersons.DataBind();
Run Code Online (Sandbox Code Playgroud)

我认为这个"空项目"是演示文稿/ UI,所以我喜欢把它放在aspx中.它还使代码隐藏更简单.