views:

1376

answers:

3

I'm working with a winForms app that has a listView. That listView has multi-select enabled and I have many, many items in the list (in row view).

When I select the last row (i.e. item), then shift-click the 5000th row, SelectedIndexChanged fires 5000 times. If this happens, I end up in a very nasty loop. The last row clicked is not guaranteed to be the last item in the "SelectedItems" list. How do I get the actual item clicked?

EDIT: Better clarification: How do I get my hands on the ListViewItem that CAUSED this particular iteration of the SelectedIndexChanged event? ... even if I have to check all 5000 of them. I need to know which one I'm looking at. EventArgs does not have an index property, and sender is the ListView, not the ListViewItem.

Any thoughts?

A: 

Here's the best solution I can think of. Handle the ListView's OnMouseMove event. Whenever the mouse moves, record the location of the mouse. Then when you get a SelectedIndexChangedEvent you can call ListView.FindNearestItem(SearchDirectionHint, Point) and pass in the last mouse coordinates as the Point parameter. This should give you the item that was actually clicked.

Note you can't depend on it actually returning an item though. It's perfectly possible to select an item without every using the mouse. A couple of tabs and space bar will do the trick. But for actual clicks, this should do the trick.

JaredPar
A: 

There is a method on ListView called HitTest. By handling the event MouseClick you can determine what the last item that was clicked.

If you want to figure out what the last selected item was, don't forget the keyboard. In a list view control, you can hold down Ctrl+(arrow key) to move the focus rectangle, and then hit Ctrl+Space to add to the selection. If you want the last selected item, you will have to handle this too.

Matt Brunell
+5  A: 

OH, FOR THE LOVE OF PETE... (* feels dumber than a rock *)

I found my answer. Note that I am using SelectedIndexChanged. There is another event that I should have been using: ItemSelectionChange.

When using that event, I now have events that can tell me which items changed in the selection and it tells me if the item was Selected or Unselected. It's beautiful.

I hope that helps others that are fighting this issue.

Jerry