Waren
Waren

Reputation: 313

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.

Upvotes: 7

Views: 33869

Answers (5)

Henrik Larsen
Henrik Larsen

Reputation: 36

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);
                }

            }
        }

Upvotes: 0

Birek
Birek

Reputation: 93

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);
  }
}

Upvotes: 2

CharithJ
CharithJ

Reputation: 47510

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();
        }
    }
}

Upvotes: 12

Asdfg
Asdfg

Reputation: 12203

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)
}

Upvotes: 6

Thorsten Dittmar
Thorsten Dittmar

Reputation: 56697

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...

Upvotes: 2

Related Questions