Ronald McDonald Ronald McDonald - 2 months ago 10
ASP.NET (C#) Question

Remove selected Items from Asp.net ListBox

I need to remove the selected items from a ListBox in asp.net. I keep finding examples for windows forms but not for asp.net.

I have a button click event that copies all items from one listbox to another. I want to be able to select individual items from the second listbox and click a button to remove them.

protected void btnAddAllProjects_Click(object sender, EventArgs e)
{

foreach (ListItem item in lstbxFromUserProjects.Items)
{
lstBoxToUserProjects.Items.Add(item.ToString());
}


}

protected void btnRemoveSelected_Click(object sender, EventArgs e)
{}

Answer

If you just want to clear the selected items then use the code below:

        ListBox1.ClearSelection();

        //or

        foreach (ListItem listItem in ListBox1.Items)
        {
            listItem.Selected = false;
        }

If you mean to what to actually remove the items, then this is the code for you..

        List<ListItem> itemsToRemove = new List<ListItem>();

        foreach (ListItem listItem in ListBox1.Items)
        {
            if (listItem.Selected)
                itemsToRemove.Add(listItem);
        }

        foreach (ListItem listItem in itemsToRemove)
        {
            ListBox1.Items.Remove(listItem);
        }
Comments