65.9K
CodeProject is changing. Read more.
Home

Remove multiple items from ListBox

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.40/5 (9 votes)

May 13, 2010

CPOL
viewsIcon

46557

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".
<!--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);
        }
}