Select a WinForm ListView, click Delete: Trigger Code

Say I have a list item that consists of several items, I select it and click delete.
I want something to happen when the delete button is pressed (and I would like to know which item or items are selected). If possible, I would like to know how to do it.

Thank!

+5
source share
1 answer

Customize your ListView to have an event handler for the KeyDown event. Then verify that the key was pressed by the delete key. Then use SelectedItems to see which items are selected and delete them. Remember to do it from the bottom up, because the collection of SelectedItems will be constantly changing.

private void listView1_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyData == Keys.Delete)
        {
            for (int i = listView1.SelectedItems.Count - 1; i >= 0; i--)
            {
                ListViewItem li = listView1.SelectedItems[i];
                listView1.Items.Remove(li);
            }
        }
    }
+6
source

All Articles