Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / ASP.NET

Remove multiple items from ListBox

3.40/5 (9 votes)
9 Feb 2011CPOL 46.5K  
There is no direct way to remove multiple selected items from ListBox when SelectionMode of ListBox is set to Multiple. So there is a small solution to handle this situation.In following Example ListBox lstCity contains multiple cities and SelectionMode is set Multiple.
There is no direct way to remove multiple selected items from ListBox when SelectionMode of ListBox is set to "Multiple". So there is a small solution to handle this situation.

In following Example ListBox "lstCity" contains multiple cities and SelectionMode is set "Multiple".

XML
<!--List contains cities and SelectionMode is set to "Multiple"-->
    <asp:ListBox ID="lstboxTest" runat="server" SelectionMode=Multiple>
        <asp:ListItem>Mumbai</asp:ListItem>
        <asp:ListItem>Delhi</asp:ListItem>
        <asp:ListItem>Kolkata</asp:ListItem>
        <asp:ListItem>Pune</asp:ListItem>
        <asp:ListItem>Chennai</asp:ListItem>
        <asp:ListItem>Banglore</asp:ListItem>
        <asp:ListItem>Noida</asp:ListItem>
        <asp:ListItem>Gurgaon</asp:ListItem>
    </asp:ListBox>

  
    <!--On click of button remove all selected Cities from list-->
    <asp:Button ID="btnRemove" runat="server" Text="Remove" />


In Codebehind add following namespace at the top of the page.

using System.Collections.Generic; 


Write following lines of code to remove multiple Items from ListBox "lstCity" inside Click event of btnRemove.

1. Create List of ListItem "lstSelectedCities".

2. Loop through the ListBox lstCity's Items collection and add selected ListItem in the List "lstSelectedCities".

3. Loop through the List "lstSelectedCities" and remove ListItems from ListBox "lstCity" that are in lstSelectedCities List by using lstCity.Items.Remove(ListItems);

protected void btnRemove_Click(object sender, EventArgs e)
{
        //1. Create a List of ListItem
        List<ListItem> lstSelectedCities = new List<ListItem>();
   
        //2. Loop through lstCity's Item Collection
        // Add selected ListItem to the List "lstSelectedCities".
        foreach (ListItem liItems in lstCity.Items)
        {
            if (liItems.Selected == true)
            {
                lstSelectedCities.Add(liItems);
            }
        }
    
        //3. Loop through the List "lstSelectedCities" and
        // remove ListItems from ListBox "lstCity" that are in 
        // lstSelectedCities List
        foreach (ListItem liSelected in lstSelectedCities)
        {
            lstCity.Items.Remove(liSelected);
        }
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)