c# - 下拉列表无法识别列表项

标签 c# asp.net drop-down-menu

我有一个下拉列表,其填充是由如下所示的函数完成的:

public void filldropdown()
{
    MySqlConnection conn = new MySqlConnection(connectionString);
    conn.Open();
    string query = "select * from category";
    MySqlCommand cmd = new MySqlCommand(query,conn);
    MySqlDataReader dr = cmd.ExecuteReader();
    if(dr.HasRows)
    {
        DropDownList1.Items.Add(new ListItem("---select---","null"));
        while(dr.Read())
        {
            DropDownList1.DataSource = dr;
            DropDownList1.DataTextField = "name";
            DropDownList1.DataValueField = "id";
            DropDownList1.DataBind();
        }
    }
    conn.Close();
}

aspx 中的下拉列表是 -:

<asp:DropDownList OnSelectedIndexChanged="showlabel" AutoPostBack="true"    ID="DropDownList1" runat="server">
        <asp:ListItem Text="---select---" Value="null"></asp:ListItem>
    </asp:DropDownList>

我只是不知道第一个项目是如何来自数据库而不是“---select---”

感谢您的宝贵时间。

最佳答案

您需要设置AppendDataBoundItems DropdownList 的属性为 true。否则,数据绑定(bind)将清除现有值。

关于c# - 下拉列表无法识别列表项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18592824/

相关文章:

javascript - 使用 Greasemonkey 更改变量或激活 JS 链接的 <select> 下拉列表

jquery - Bootstrap - 在移动菜单中下拉打开正常,无法关闭下拉

c# - 如何捕获监视文件夹删除事件

sql - 使用 vb.net 在 SQL 中保存日期

javascript - 如何使用javascript获取表格中的所有Div

Android自定义下拉/弹出菜单

c# - 图像调整器 'Use .Build(new Image Job(source, dest, settings, dispose Source, add FileExtension)).Final Path instead'

c# - 跟踪 Entity Framework 中删除的对象数量和类型的方法

c# - 使用具有虚拟值的字典是一种不好的做法吗

c# - 在 AngularJS 项目中访问 .net Web.Config