Sorting Numeric Values in a ListBox

I’m using column sorting for the listbox control. Numeric values, because they are treated as strings do not sort properly, as a result I get:


When what I am after is:


What, if any is the easiest work around for this? Has anyone come up with a slick way to deal with this?


The CompareRows event allows you to make comparisons on other than the default basis. You get variables row1, row2, and column to tell you what is about to be compared, and a ByRef result to put the answer in, so…

if column = kMyNumericColumn then dim a1, a2 as double a1 = CDbl(me.Cell(row1,column)) a2 = CDbl(me.Cell(row3,column)) if a1<a2 then result = -1 elseif a1>a2 then result = 1 else result = 0 end if return true //this means you actually did a comparison else return false //if it's not the numeric column, this tells the program to go ahead and use the default sort end if

Very good. Thank you!

I covered this is last week’s ListBox webinar (which also has a sample project). You can view the webinar and download the project from here:

Thank you Paul.

On ComapreRows:

If Val(Me.Cell(row1,2))> Val(Me.cell(row2,2)) then
End if
Return True //

I just see that if we return 0 (result = 0) then the listbox is sometimes sorted.

Make a listbox with 2 or 3 columns with anything in them.
Enter in the event CompareRows

result = 0

then launch and click the header to sort. Click one time on a column, nothing happens (depending of ascending or descending), click again, it’s sorted. Clicxk again, nothing more happens (it stay sorted as it is).
Click another columns, same trouble (depending of ascending or descending).

is there a way to do this sort by clicking another control instead of the header?

Set the listbox SortedColumn and ColumnSortDirection properties and then call the Sort method.

You can also use Select Case to work on multiple columns, for example (inside CompareRows event):

[code] Select Case column
Case 1, 2, 3, 4
dim a1, a2 As Double
a1 = CDbl(me.Cell(row1,column))
a2 = CDbl(me.Cell(row2,column))

if a1<a2 then
  result = -1
elseif a1>a2 then
  result = 1
  result = 0
end if
return true //this means you actually did a comparison

return False //use the default sort
End Select[/code]

Where can I download Paul’s project? I watched the excellent video, but the youtube page sends me back to the list of videos, and I do not see the project on the video list page.

Look at the Examples that come with Xojo: Desktop -> Controls -> ListBox -> ListBoxExample.xojo_binary_project