.NET ListView: Event After Selection Changes

In the ListView control, I need to fire the event after changing the selection, but only once for each user action. If I just use SelectedIndexChanged, this event fires twice in most cases (once when the previous item is not selected and again when a new item is selected) if the user just clicked on the control once .

Two events fire quickly one after another, but the calculation that I perform when I change the selection takes time (almost a second), so it runs twice and slows down the interface.

What I want to do is to do it only once per user action (doing it before the new item is selected is useless), but I don’t know if the event is only the first of the pair (to skip the first calculation), because if the user simply deselected the selected item, it will fire only once.

I cannot use the Click or MouseClick events because they do not fire at all if the user clicked outside the list to remove the selection.

Thank you for your help.

+4
source share
3 answers

Here is my solution in VB.NET using the method described in ObjectListView as suggested by the Grammar :

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 
+2
source

I also found this annoying, so there is a SelectionChanged event in the ObjectListView (the open source shell around .NET WinForms ListView) that happens only once per user action.

With direct .NET ListView, when an item's selection state changes, it fires the SelectedIndexChanged event. So, for a simple click on another row, you get one event to deselect a previously selected row, and another to select a new one.

If you select a hundred lines and select a different line, you will receive the 101 SelectedIndexChanged event - this could be a pain in the kingdom.

In any case, with an ObjectListView, you get only one SelectionChanged event, regardless of how many rows were selected or canceled.

+3
source

If you want your calculation to be performed only when a new item is selected, you can check if there is a new SelectedIndex! = -1

-2
source

All Articles