1

i have a Drop-down list which is data bounded from a table and i want to remove an item from it on page load, but the problem is nothing is happening from this piece of code:

on page load:

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>

the sqldata source code on aspx page:

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

Note : dropdownlist is displaying the all bounded values including value to be deleted (compiler) - image here

Jai hind
  • 85
  • 1
  • 11

2 Answers2

0

You have to use AppendDataBoundItems="False" and set DataSource in PageLoad event. Next you will be able to remove your Item

Change DropDownList like this

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

Add DataSource and Remove item using FindByText() method

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);
    }
}
M. Wiśnicki
  • 6,094
  • 3
  • 23
  • 28
  • or set `DropDownList1.DataSource = null;` then reassign when wanting to bind to a different DataSource would work too.. – MethodMan Dec 01 '16 at 19:32
0

You can try removing at PreRender event.

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);
    }
}
Win
  • 61,100
  • 13
  • 102
  • 181