How to remove selected items from a ListView by pressing the Delete button?

advertisements

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.


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