2

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.

4

1 回答 1

2

这肯定会出错,双击并不能保证选择了某个项目。它也可能取消选择一个项目,您的代码将崩溃。除了添加测试来检查 SelectedItems 是否为空,更好的鼠标陷阱可能是找到被双击的确切项目。请改用 MouseDoubleClick 事件,以便获取鼠标位置,然后使用 ListView.HitTest() 方法。像这样:

    private void listView1_MouseDoubleClick(object sender, MouseEventArgs e) {
        var item = ((ListView)sender).HitTest(e.Location);
        if (item != null) {
            // etc..
        }
    }
于 2013-10-16T13:29:54.037 回答