I have an ownerdrawn ListBox on a form (Windows Forms) binding to a datasource (BindingList). I need to provide an option to select all items (up to 500000) really fast.
This is what I am currently doing:
for (int i = 0; i < listBox.Items.Count; i++)
listBox.SetSelected(i, true);
This is incredibly slow and not acceptable. Does anybody know a better solution?
Assuming this is a Windows Forms
problem: Windows Forms will draw changes after each selected item. To disable drawing and enable it after you're done use the BeginUpdate()
and EndUpdate()
methods.
listBox.BeginUpdate();
for (int i = 0; i < listBox.Items.Count; i++)
listBox.SetSelected(i, true);
listBox.EndUpdate();
I could not find a way that was fast enough to be acceptable. I tried BeginUpdate/EndUpdate which helped but still took 4.3 seconds on a intel core i5 laptop. So this is pretty lame but it works - at least it does in the IDE. the ListBox is called lbxItems on the form I have a button called Select All. In that button's click event I have:
//save the current scroll position
int iTopIndex = lbxItems.TopIndex;
//select the [0] item (for my purposes this is the top item in the list)
lbxItems.SetSelected(0, true);
// put focus on the listbox
lbxItems.Focus();
//then send Shift/End (+ {END}) to SendKeys.SendWait
SendKeys.SendWait("+{END}");
// restore the view (scroll position)
lbxItems.TopIndex = iTopIndex;
result: This selects 10,000 items in a few milliseconds. The same as it would it I actually used the keyboard
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With