问题
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.
回答1:
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();
}
}
}
回答2:
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)
}
回答3:
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);
}
}
回答4:
Try this:
// 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 a SelectedItems property. To make sure that you're not changing the collection you're iterating on, I'd copy that collection first:
Seems the above (using AddRange) did not work. I thought that removing the items by iterating over the SelectedItems enumerable would cause an exception, but obviously it does not. So my original code code be modified to match the other answers... sorry for posting non-functional code...
回答5:
I know this is a bit unrelated but In WPF the mentioned methods did not work for me. I had to create a copy of the selected items and use these to remove items in the listview.:
private void ListBox_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
{
if (e.Key == System.Windows.Input.Key.Delete)
{
var lst = new List<object>();
foreach (var itemSelected in ListBox.SelectedItems)
{
lst.Add(itemSelected);
}
foreach (var lstitem in lst)
{
ListBox.Items.Remove(lstitem);
}
}
}
来源:https://stackoverflow.com/questions/6829678/how-to-delete-selected-items-from-a-listview-by-pressing-the-delete-button