.NET ListView: event after changing selection
.net, listview, winforms
Solution
Here's my solution in VB.NET, using the technique described in ObjectListView as suggested by Grammarian:
Private idleHandlerSet As Boolean = False
Private Sub listview1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles listview1.SelectedIndexChanged
'' may fire more than once
If Not idleHandlerSet Then
idleHandlerSet = True
AddHandler Application.Idle, New EventHandler(AddressOf listview1_SelectionChanged)
End If
End Sub
Private Sub listview1_SelectionChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)
'' will only fire once
idleHandlerSet = False
RemoveHandler Application.Idle, New EventHandler(AddressOf listview1_SelectionChanged)
DoSearch()
End Sub
Problem
On the ListView control, I need an event to fire after the selection changes, but only once per user action. If I simply use the SelectedIndexChanged, that event fires twice in most cases (once when the previous element is unselected and once more when the new element is selected) event if the user only clicked on the control once. The two events fire quickly one after the other, but the computation I do when the selection changes takes time (almost a second) so it is done twice and slows down the interface. What I want to do is only do it once per user action (doing it before the new element is selected is useless) but I have no way of knowing if the event is just the first of a pair (in order to skip the first computation) because if the user just deselected the selected element, it will fire only once. I can't use the Click or MouseClick events because those don't fire at all if the user clicked outside the list to remove the selection. Thanks for your help.