下拉列表无法识别listitem

时间:2013-09-03 12:52:27

标签: 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>

我只是不知道地球上的第一个项目是如何来自数据库而不是“---选择---”

这是你的时间。

4 个答案:

答案 0 :(得分:4)

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

答案 1 :(得分:1)

您已更改了DataSource:

        DropDownList1.DataSource = dr;
        DropDownList1.DataTextField = "name";
        DropDownList1.DataValueField = "id";
        DropDownList1.DataBind();

当您将DataSource更改为dr时,它将删除您当前的---select---项目(正如预期的那样)。

您需要在绑定DataSource后添加它。

 DropDownList1.Items.Insert(0, new ListItem("---- select ----", 0));
 DropDownList1.SelectedIndex = 0;

答案 2 :(得分:0)

试试这个

    public void filldropdown()
    {
        MySqlConnection conn = new MySqlConnection(connectionString);
        conn.Open();
        string query = "select * from category";
        MySqlCommand cmd = new MySqlCommand(query, conn);

        MySqlDataAdapter da = new MySqlDataAdapter(cmd);
        DataSet ds=new DataSet();
        da.Fill(ds);
        DropDownList DropDownList1 = new DropDownList();
        DropDownList1.DataSource = ds;
        DropDownList1.DataTextField = "name";
        DropDownList1.DataValueField = "id";
        DropDownList1.DataBind();
        DropDownList1.Items.Insert(0,new ListItem("---select---", "null"));
        conn.Close();
    }

答案 3 :(得分:0)

有一些方法可以将项目添加到数据绑定下拉列表,例如我使用Insert指定插入位置(在哪个位置)。

DropDownList1.Items.Insert(1, "-- Select --");