Sort Method (ListView)

Purpose

Sorts the items in a ListItems collection.

Syntax

ListView.Sort column%, compare%

Description

Sorts the ListView control using the specified column% as sort key. The value for column% starts with 0, where the ColumnHeader indices start with 1.

It is common to sort a list when the column header is clicked. For this reason, the Sort property is commonly included in the ColumnClick event to sort the list using the clicked column. It is also common to sort the list in ascending order first and when the column header is clicked again in descending order.

compare% specifies a value that determines whether ListItem objects in a ListView control are sorted in ascending or descending order and which compare mode to use. The value for compare% is the same as for Mode Compare (0 = Binary, 1 = Text - case insensitive, etc). The descending sort order is specified by setting the appropriate bit in the compare% value ($10000)

$0 - Ascending order. Sorts from the beginning of the alphabet (A-Z) or the earliest date. Numbers are sorted as strings, with the first digit determining the initial position in the sort, and subsequent digits determining sub-sorting.

$10000 - Descending order. Sorts from the end of the alphabet (Z-A) or the latest date. Numbers are sorted as strings, with the first digit determining the initial position in the sort, and subsequent digits determining sub-sorting.

Example

Global a$, n As Int32

Ocx ListView lv = "", 10, 10, 400, 200 : .View = 3 : .FullRowSelect = True : .GridLines = True

For n = 1 To 4 : lv.ColumnHeaders.Add , , "Column" & n : lv.ColumnHeaders(n).Alignment = 2 : Next n

For n = 1 To 4

lv.Add , , ""

a$ = Rand(10) & ";" & Rand(10) & ";" & Rand(10) & ";" & Rand(10)

lv(n).AllText = a$

Next n

Do : Sleep : Until Me Is Nothing

 

Sub lv_ColumnClick(ColumnHeader As ColumnHeader)

// ColumnHeader objects do not store their sort direction...

// ...so you can use Tag instead

If Val(ColumnHeader.Tag) = 0 Or Val(ColumnHeader.Tag) = 1

lv.Sort ColumnHeader.Index - 1, $1

ColumnHeader.Tag = 2

Else

lv.Sort ColumnHeader.Index - 1, $10000

ColumnHeader.Tag = 1

EndIf

EndSub

The ListView lv1 is sorted case-insensitive (compare% = 1) and the sort order is toggled when the column is clicked again.

Remarks

For the possible values for Mode Compare see here.

See Also

ListView, ColumnClick

{Created by Sjouke Hamstra; Last updated: 23/10/2014 by James Gaite}