如何在页面加载时删除数据有界下拉列表项?

时间:2016-12-01 19:18:31

标签: c# asp.net drop-down-menu listitem databound

我有一个下拉列表,它是从表中限定的数据 我想在页面加载时从中删除一个项目,但问题是这段代码没有发生任何事情:

页面加载

protected void Page_Load(object sender, EventArgs e)
{
    ListItem itemToRemove = DropDownList1.Items.FindByText("compiler"); //just want to remove this value
    if (itemToRemove != null)
    {
        DropDownList1.Items.Remove(itemToRemove);
    }
}

**dropdownlist code on aspx page**:

<asp:DropDownList ID="DropDownList1"  AppendDataBoundItems="true" runat="server" DataSourceID="SqlDataSource1" DataTextField="qpname" DataValueField="qpname" Height="16px" Width="116px" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged" AutoPostBack="True">
  <Items>
   <asp:ListItem Text="Select" Value="" />
   </Items>
</asp:DropDownList>

aspx页面上的sqldata源代码:

<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:projectConnectionString %>" SelectCommand="SELECT [qpname] FROM [A1_quespapers]"></asp:SqlDataSource>

注意:dropdownlist显示所有有界值,包括要删除的值(编译器) - image here

2 个答案:

答案 0 :(得分:0)

您必须使用AppendDataBoundItems="False"并在PageLoad事件中设置DataSource。接下来,您将能够删除Item

像这样更改DropDownList

<asp:DropDownList ID="DropDownList1"  AppendDataBoundItems="false" runat="server"  DataTextField="qpname" DataValueField="qpname" Height="16px" Width="116px" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged" AutoPostBack="True">

       

使用FindByText()方法

添加数据源和删除项目
protected void Page_Load(object sender, EventArgs e)
{


    DropDownList1.DataSource = SqlDataSource1;
    DropDownList1.DataBind()

    ListItem itemToRemove = DropDownList1.Items.FindByText("compiler");   
    if (itemToRemove != null)
    {
        DropDownList1.Items.Remove(itemToRemove);
    }
}

答案 1 :(得分:0)

您可以尝试在 PreRender 事件中删除。

protected void Page_PreRender(object sender, EventArgs e)
{
    ListItem itemToRemove = DropDownList1.Items.FindByText("compiler"); //just want to remove this value
    if (itemToRemove != null)
    {
        DropDownList1.Items.Remove(itemToRemove);
    }
}