Jim Lanflte
Jim Lanflte

Reputation: 43

ListView with an empty SelectedItems , when DoubleClick handler is called

I have a WinForm app that has a ListView in it, with a DoubleClick event handler assigned to it. Theoretically , only items are "clickable" , so it should be impossible to enter the event handler with no selected items, and so it is for 99% of cases. However, every once in a while, I catch an exception of InvalidAgrument as my handler try to access list_view.SelectedItems[0], and there I see that it does actually empty.

When I try to reproduce, it takes an aggressive clicking session to do it. But it's done, I can sometimes see the cursor in the middle of a valid entity , which makes me suspect it might be some racing condition.

Upvotes: 2

Views: 707

Answers (1)

Hans Passant
Hans Passant

Reputation: 941545

This can certainly go wrong, a double-click doesn't guarantee that an item is selected. It may also de-select an item, your code will crash. Short from adding the test to check that SelectedItems isn't empty, the possible better mouse trap is to find the exact item that was double-clicked. Use the MouseDoubleClick event instead so you get the mouse position, then use the ListView.HitTest() method. Like this:

    private void listView1_MouseDoubleClick(object sender, MouseEventArgs e) {
        var item = ((ListView)sender).HitTest(e.Location);
        if (item != null) {
            // etc..
        }
    }

Upvotes: 2

Related Questions