C # Select all items in a ListBox - pause event processing

See: ListBox select all items

I have a ListBox and I need to select all the items. The only problem is that I have event handlers in the ListBox.SelectIndexChanged event, which does some things that are CPU intensive. Selecting elements in a loop here causes the program to fire the SelectIndexChanged event at each iteration of the loop.

I included a loop in Suspend / ResumeLayout () as follows:

SuspendLayout(); for (int i = 0; i < listBox.Items.Count; i++) listBox.SetSelected(i, true); ResumeLayout(); 

but it still fires the event and still takes a long time to update the selection.

I could fix the problem with a simple boolean flag that I switch when the update starts, but if there is an easier way to resolve this issue, that would be great.

Thanks.

+4
source share
1 answer

Another option (in addition to using the logical flag) is to unregister the event handler before the loop and reregister after the loop.

 listBox.SelectIndexChanged -= listBox_selectIndexChanged; for (int i = 0; i < listBox.Items.Count; i++) listBox.SetSelected(i, true); listBox.SelectIndexChanged += listBox_selectIndexChanged; 
+7
source

All Articles