Question Listbox faster method for selecting all

juhah

Active member
Joined
Apr 16, 2007
Messages
28
Programming Experience
3-5
I have a listbox control that has a selection mode "MultiSimple" (I've also tried MultiExtended). I also have a button that uses this code to select all the items in the list:

Dim i As Integer
For i = 0 To ListBox1.Items.Count - 1
ListBox1.SetSelected(i, True)
Next i

It works ok but the problem is that it's very slow. I have cases where there are 60 000 items in the listbox, and it takes forever to select them all. Is there any function that would select all at once (Just like ListBox1.ClearSelected() unselects all instantly)?

Or some other control that would do the trick?
 
You can call BeginUpdate/EndUpdate methods, to prevent the Listbox to paint during items being selected. Though for this amount of items I don't think you'll see much of a difference, it's just too much. 60.000 items in a UI element sounds like information overload to me. An alternative could be a "Selection All" checkbox that denote that all items should be considered selected for any later processing, without actually selecting anything in the listbox itself.

You could try DataGridView control, it may be better for handling display of larger amounts of data, it also has a SelectAll method. This control was added to .Net 2.0 so, you may not be able to use it if you're really on .Net 1.
 
Further research reveals: If you have selection mode MultiExtended and manually select first item, scroll to bottom and Shift-click last item, then all items are immediately selected. So the control is capable of doing this operation very fast, only that SetSelected involves calls and windows messages that take longer time. Which lead me to believe there is a API call that will allow it, and there is; the LB_SELITEMRANGEEX message:
VB.NET:
Declare Function SendMessage Lib "user32.dll" Alias "SendMessageA" (ByVal hwnd As IntPtr, ByVal wMsg As Int32, ByVal wParam As UInt16, ByVal lParam As UInt16) As Int32
Const LB_SELITEMRANGEEX As Int32 = &H183
example call:
VB.NET:
SendMessage(Me.ListBox1.Handle, LB_SELITEMRANGEEX, 0, CUShort(Me.ListBox1.Items.Count - 1))
This selected 60.000 items in 61ms for me, so that is rather fast.

Note, I seem to recall the unsigned data types support wasn't fully developed with .Net 1, so you may have to use the Int32 data type instead of UInt16 and just limit yourself to the given value range. The Listbox seems to go ballistic above that number anyway.
 
This solved the problem, thanks a lot! :)

I had to use Int32 data type in the declaration since UInt16 wasn't supported.
 
Back
Top