How to use the SortedOn property
The SortedOn property gives you control over the criteria which SBList uses to sort
list items when you have the Sorted property set to true. You can base your sort on
the text which appears in the list (just like a standard list box), or on the .ItemText
value for each list item, or on the .ItemData value for each item.
A good way of visualising this feature is to think about a list containing all the
files in your Windows directory. The list always has the same columns of information;
File name, Size, and Date. When you add the files to a standard list box, the only way
to sort them would be on File name, unless you displayed the columns in a different
order so that Size was the first column, and then they would appear in order of size.
There would be no way of keeping the columns in the same order because the sort method
only works on the text of each list item. With an SBList you can sort your items on
the .ItemText value, which is transparent to the user, and always have your columns
in the same order.
For this demonstration you will need to draw a form which has a single SBList on it.
Set the Sorted property to true. You will also need a control array of three command
buttons - set the caption of Command1(0) to "By Name", Command1(1) to "By Size" and
Command1(2) to "By Extension".
1. Insert the following code into your Form_Load event:
With SBList1
.TabWidth(0) = 100
.TabWidth(1) = 140
End With
This sets up our list columns. The first column (from pixel 0 to 99) will hold the
file name less the file extension. The second column (from pixel 100 to 139) will hold
the file extension, and the third column (from pixel 140 onwards) will hold the file size.
2. Insert the following code into your Command1_Click event:
SBList1.Clear
' When Index is 0, we sort on Common$ (.List)
' When Index is 1, we sort on Size& (.ItemData)
' When Index is 2, we sort on Ext$ (.ItemText)
SBList1.SortedOn = Index
P$ = "C:\"
D$ = Dir$(P$ & "*.*")
Do While D$ <> ""
' Does the current file have an extension?
If Instr(D$, ".") Then
Ext$ = Mid$(D$, Instr(D$, ".") + 1)
File$ = Left$(D$, Instr(D$, ".") - 1)
Else
Ext$ = ""
File$ = D$
End If
Size& = FileLen(P$ & D$)
' The \t code represents the Tab character
Common$ = File$ & "\t" & Ext$ & "\t" & Size&
SBList1.AddPacket -1, Common$, Ext$, Size&
D$ = Dir$
Loop
When you run this program and click the three buttons, the list will fill up sorted on
either the file name, extension or size. The point here is that (a) we didn't have to
write three routines to fill the list in three different ways, (b) we didn't have to
change the order of the columns in order to display the list items in a different order,
and (c) we didn't need two lists; one list to sort the items and a
second list to display them.
Note: When you sort on the .ItemData value, the list is sorted into correct numeric
order (1, 2, 3, 4 ...) as opposed to ANSI sort order (1, 10, 11, 2 ...).
Topic devised by Andy Groom.