首页 文章

根据以前的下拉列表选择填充下拉列表

提问于
浏览
1

在我的ASP网站中,我有两个下拉列表,第一个有用户选择的四个选项,基于此选项,第二个下拉列表将从选定的数据库列数据中填充 . 我试图以编程方式填充这些列表,而不是通过数据源绑定它们

我目前的代码有两个问题:

1. Within my 'onselectedIndex changed' method I cannot trigger my event if I wish to click the first element in the dropdown list, I have to click another item then re-click the first for it too trigger. I do have AutoPostBack set to true

2. When the event does trigger the database data is not populating the second dropdownlist, It is correctly populating with the correct amount of rows for the dataset, but not displaying the data.

一旦从第一个下拉列表中选择第一个元素,即'咖啡名称',那么第二个列表将填入正确的行号,即3但不包含正确的数据

当前代码:

protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
    {
        string option = DropDownList1.SelectedValue;
        // If the selected element is 'Coffee Name' run the method.
        if (option == "Coffee Name")
        {
            bindCoffeeNames();
        }
    }



    private void bindCoffeeNames()
    {
        Query the DB and bind the data to the second dropdown list.
        SqlConnection sqlcon = new SqlConnection(connstring);
        SqlCommand sqlcmd = new SqlCommand("select coffeeName from Coffees ORDER BY coffeeName ASC", sqlcon);
        SqlDataAdapter adp = new SqlDataAdapter(sqlcmd);
        DataSet ds = new DataSet();
        adp.Fill(ds);
        DropDownList2.DataSource = ds.Tables[0];
        DropDownList2.DataBind();

    }

1 回答

  • 0
    • Autopostback仅在更改时触发 . 您想要将默认占位符插入到
      下拉列表 . 你可以在这样的代码中做到这一点:
    dropdownlist1.Items.Insert(0, new ListItem("Select an item", String.Empty));
    dropdownlist1.SelectedIndex = 0;
    

    或者在标记中:

    <asp:DropDownList ID="ddlPersons" runat="server" AppendDataBoundItems="true" DataValueField="ID" DataTextField="Name">
    <asp:ListItem> -- please select person -- </asp:ListItem>
    </asp:DropDownList>
    
    • 将此行添加到bindCoffeeNames:

    DropDownList2.DataTextField = "coffeeName";

    另外,最好指定一个 DataValueField (您还必须更改查询以返回 CoffeeId ,但这不是必需的)

相关问题