【问题标题】:Populating a dropdownlist based on a previous dropdownlist selection根据先前的下拉列表选择填充下拉列表
【发布时间】:2013-03-21 00:32:25
【问题描述】:

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

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

1.在我的“onselectedIndex changed”方法中,如果我想单击下拉列表中的第一个元素,我将无法触发我的事件,我必须单击另一个项目,然后重新单击第一个元素以触发它。我确实将 AutoPostBack 设置为 true

2。当事件确实触发数据库数据未填充第二个下拉列表时,它正确填充了数据集的正确行数,但不显示数据。

一旦从第一个下拉列表中选择第一个元素,即“咖啡名称”,则第二个列表会填充正确的行号,即 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();

    }

【问题讨论】:

    标签: c# asp.net


    【解决方案1】:
    1. 自动回发只会在更改时触发。您想将默认占位符插入到 a
      下拉列表。你可以用这样的代码来做:

      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>
      
    2. 将此行添加到 bindCoffeeNames:

      DropDownList2.DataTextField = "coffeeName";

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

    【讨论】:

    • 非常感谢我使用了占位符“空白”默认项目。但是数据字段工作得很好。再次谢谢你。我会尽可能将你的答案标记为正确
    猜你喜欢
    • 2011-11-04
    • 1970-01-01
    • 1970-01-01
    • 2015-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-05
    相关资源
    最近更新 更多