Sorting Combobox (Descending & Ascending order)

It would be really good (and a time-saver) if the Xojo team added a Sort method to the ComboBox control, which allowed you to sort either descending or ascending. There is a Sort method for arrays in Xojo, but it only supports ascending.

I decided to create an extension method for the ComboBox, which will permit you to sort in either direction. (I hope you all find this useful).

Steps:

  1. Create a Module (and name it whatever you want)
  2. Create an Enumeration in your module and name it: “SortDirection”
  3. Add 2 Declarations to your enumeration:
    a) DescendingOrder
    b) AscendingOrder
  4. Create a method in the module named “Sort” (or whatever you want to name it)
  5. Add the following parameters to your method:
    Extends ctrl As DesktopComboBox, sortOrder As SortDirection
    5a) *Feel free to add a return type if you need one, but I left mine blank

Step 6 (Here’s the code I wrote):

// This extension method will sort the contents of a ComboBox in either Ascending or Descending order

if ctrl.RowCount > 0 then
dim items() as String, reverseItems() as String

for x as integer = 0 to ctrl.RowCount - 1 // add items in the combobox to the items array
items.Add(ctrl.RowTextAt(x))
next

items.Sort // sort the array (ascending order)

if SortDirection.DescendingOrder = sortOrder then // check to see if a descending sort was requested
// loop through newly sorted items array in reverse order and add them to the reverseItems array
for y as integer = items.LastIndex DownTo 0
reverseItems.Add(items(y))
next

items = reverseItems // Now copy the contents of the reverseItems array to the items array
end if

ctrl.RemoveAllRows() // Clear the comobox and then repopulate it with the newly sorted data
for z as integer = 0 to items.Count - 1
ctrl.AddRow(items(z))
next
end if

============================

To test it, add a combobox to your Window and in the Window Opening event, I added the following test code:

combobox1.addrow(“World”)
combobox1.addrow(“Hello”)
combobox1.addrow(“10”)
combobox1.addrow(“1”)

I then added 2 Buttons to my Window (Button1 and Button2).
Button1 (when clicked) will sort the combobox in ascending order.
Button2 (when clicked) will sort the combobox in descending order.

Here is the code for Button1: combobox1.Sort(SortDirection.AscendingOrder)
Here is the code for Button2: combobox1.Sort(SortDirection.DescendingOrder)

Now all you have to do is “Run” your project and test it.