2016-12-01 67 views
1

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

页负载:

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> 

注:dropdow NLIST是显示所有有界值,包括价值将被删除(编译) - image here

+0

尝试把你的代码的IsPostBack – Webruster

回答

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); 
    } 
} 
+0

或设置'DropDownList1.DataSource = NULL;!想要绑定到不同的数据源将工作太当'然后重新分配.. – MethodMan

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); 
    } 
} 
相关问题