How to remove selected items from a ListView by clicking the delete button?

I want to remove one or more selected items from the list. What is the best way to do this? I am using C # and dotnet Framework 4.

+4
source share
4 answers

You can delete all selected items by iterating through ListView.SelectedItems and calling ListView.Remove for each item when the user presses 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(); } } } 
+10
source

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

 foreach(var v in listView.SelectedItems) { listView.Items.Remove(v) } 
+6
source

I think this is the easiest mode.

private void listView_KeyDown (object sender, KeyEventArgs e)

{

  if (e.Key == Key.Delete) { this.listView.Items.Remove(listView.SelectedItem); } } 
+3
source

Try the following:

 // Get an array of all selected items ListViewItem[] selectedItems = (from i in listView.Items where i.Selected select i).ToArray(); // Delete the items foreach (ListViewItem item in selectedItems) listView.Items.Remove(item); 

EDIT
I just noticed that the ListView class already has the SelectedItems property. To make sure that you are not changing the collection that you are executing, I will first copy this collection: Strike>

It seems the above (using AddRange ) doesn't work. I thought that deleting items by iterating over SelectedItems enumerated would throw an exception, but obviously this is not the case. So my source code will be changed according to other answers ... sorry for posting non-functional code ...

+2
source

All Articles