Sort Non-String Items in a ListView

Sort Non-String Items in a ListView

Sorting ListView columns with numeric data can be a real pain. Nonstring sorting is possible with callbacks using custom comparison functions, but this method’s drawback is that the synchronization between the display and ListItems collection is lost. It’s easier and more reliable to simply provide sortable data. Normally a list with the values 1, 2, 3, 4, 10, and 20 sorts as 1, 10, 2, 20, 3, and 4?that’s not very useful. A simple workaround is to “left-pad” the numeric data with spaces before setting the text value. Assume that you load a listview from a recordset with last name, first name, and salary:

 Const MAX_WIDTH = 15Dim szSpaces As StringDim rs As RecordsetszSpaces = Space$(MAX_WIDTH)Do Until rs.EOF	With ListView1.ListItems.Add(, , rs("LastName"))	.SubItems(1) = rs("FirstName")	.SubItems(2) = Right$(szSpaces & _		rs("Salary"), MAX_WIDTH)	End With	rs.MoveNextLoop

Now setting the ListView’s Sorted property sorts the Salary column in correct numerical order.

See also  11 Effective Keyword Research Tools and Techniques

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist