如何在页面加载中删除数据有限的下拉列表项目



我有一个下拉列表,该列表是从表界限的数据我想从页面加载中删除其中的一项,但是问题是从此代码中没有发生的:

页面加载:

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>

注意:下拉列表正在显示所有有界值,包括要删除的值(编译器) - 图片在这里

您必须使用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);
    }
}

您可以尝试在 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);
    }
}

最新更新