Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select all items in a ListBox really fast?

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?

like image 465
Norman Avatar asked Jan 22 '16 18:01

Norman


2 Answers

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();
like image 125
Myrtle Avatar answered Sep 21 '22 21:09

Myrtle


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

like image 26
jimo Avatar answered Sep 22 '22 21:09

jimo