1

我有两个DropDownList级联控件(第二个控件是根据第一个控件的选择填充的):

<asp:DropDownList ID="ddlProduct" runat="server" AppendDataBoundItems="true" 
    AutoPostBack="true" onselectedindexchanged="ddlProduct_SelectedIndexChanged">
    <asp:ListItem Value="" Selected="True"> - Product - </asp:ListItem>
</asp:DropDownList>

<asp:DropDownList ID="ddlCategory" runat="server" AutoPostBack="true" 
    OnSelectedIndexChanged="ddlCategory_SelectedIndexChanged" AppendDataBoundItems="true">
    <asp:ListItem Value="" Selected="True"> - Category - </asp:ListItem>
</asp:DropDownList>

ddlProduct.SelectedIndexChanged事件处理程序中,我有以下代码:

ddlCategory.DataSource = _productService.GetCategoryByProductId(ddlProduct.SelectedValue);
ddlCategory.DataTextField = "CategoryName";
ddlCategory.DataValueField = "CategoryId";
ddlCategory.DataBind();

用户第一次从中选择产品时ddlProductddlCategory正确填充。接下来的时间,类别中ddlCategory的附加到第一次选择的类别,依此类推。我试着输入ddlProduct.SelectedIndexChanged

ddlCategory.Items.Clear();

但该方法也删除了硬编码的项目

<asp:ListItem Value="" Selected="True"> - Category - </asp:ListItem>

我怎样才能从 ddlCategory 中删除附加的项目?

4

3 回答 3

2

您可以AppendDataboundItems="false"手动设置和插入默认项,例如在DropDownList.DataBound事件中:

protected void ddlCategory_DataBound(object sender, EventArgs e)
{
    if (ddlCategory.Items.Count > 0)
    {
            ddlCategory.Items.Insert(0, " - Category - ");
            ddlCategory.Items[0].Value = "";
            ddlCategory.SelectedIndex = 0;
        }
    }
}
于 2012-08-27T10:19:15.423 回答
1

方法调用AppendDataBoundItems="true"后手动删除和附加空项DataBind

于 2012-08-27T10:17:13.737 回答
1

删除类别项目后,您可以使用代码添加默认类别...

ddlCategory.Items.Add(new ListItem("- Category -", "0", true));
于 2012-08-27T10:17:18.497 回答