Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete selected Items from a ListView by pressing the delete button?

I want to delete one or more selected Items from a ListView. What is the best way to do that? I´m using C# and the dotnet Framework 4.

like image 262
Waren Avatar asked Jul 26 '11 11:07

Waren


People also ask

How do I remove items from list view?

You will want to remove() the item from your adapter object and then just run the notifyDatasetChanged() on the Adapter, any ListView s will (should) recycle and update on it's own.

How do I remove all items from list controls?

Use the RemoveAt or Clear method of the Items property. The RemoveAt method removes a single item; the Clear method removes all items from the list.


2 Answers

You can delete all selected items by iterating the ListView.SelectedItems collection and calling ListView.Remove for each item whenever the user pressed the delete key.

private void listView1_KeyDown(object sender, KeyEventArgs e)
{
    if (Keys.Delete == e.KeyCode)
    {
        foreach (ListViewItem listViewItem in ((ListView)sender).SelectedItems)
        {
            listViewItem.Remove();
        }
    }
}
like image 141
CharithJ Avatar answered Nov 15 '22 07:11

CharithJ


I think there is something called listView.Items.Remove(listView.SelectedItem) and you can call it from your delete button's click event. Or run a foreach loop and see if the item is selected, remove it.

foreach(var v in listView.SelectedItems)
{
   listView.Items.Remove(v)
}
like image 38
Asdfg Avatar answered Nov 15 '22 08:11

Asdfg