4

See: ListBox select all items

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

I have enclosed the loop in Suspend/ResumeLayout() like so:

SuspendLayout();

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

ResumeLayout();

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

I could fix the issue with a simple boolean flag which I toggle when I start update, but if there is a neater way of solving this, that would be great.

Thanks.

Community
  • 1
  • 1
Ozzah
  • 10,631
  • 16
  • 77
  • 116

1 Answers1

7

The other option (besides using a boolean flag) would be 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;
Bala R
  • 107,317
  • 23
  • 199
  • 210