I needed some way to ensure that, after additions to a combobox, it would be sorted. If the list is already sorted, one way to do this is to insert a new item according to an on-the-fly scan of the list. What to do if the list isn't sorted?
From what I can see, this isn't a built-in PB feature so I wrote this one. I couldn't see offloading the list into an array, sorting that, then shoving them back in, especially for only a dozen items, or so. Also, the combobox is already an array, of sorts, so I figured to just sort it directly.
This is based on the slow but compact code bubble sort. For the number of items normally found in a combobox, though, it's fast enough. To make it ignore case, you could sort Ucased items.
If there's snazzier ways to do this or I've overlooked this feature in PB, let me know.
Thanks,
Bill
Code: Select all
Declare SortComboBox(BoxID)
#ComboBox = 1
#ButtonSort = 2
If OpenWindow(0, 0, 0, 230, 120, "Combo Sort example...", #PB_Window_SystemMenu | #PB_Window_ScreenCentered)
ComboBoxGadget(1, 10, 40, 200, 21, #PB_ComboBox_Editable)
ButtonGadget(#ButtonSort, 20, 80, 50, 25, "Sort")
;Generate some words
For i = 1 To 40 ;Number of items in combo box
a$ = ""
For j = 1 To 10 ;Number of characters per word
a$ = a$ + Chr(Random(25) + 65) ; Make "words"
Next
AddGadgetItem(#ComboBox, -1, a$); Load up with words
Next
Repeat
Event = WaitWindowEvent()
Select Event
Case #PB_Event_Gadget
Select EventGadget()
Case #ButtonSort: SortComboBox(#ComboBox)
EndSelect
EndSelect
Until Event = #PB_Event_CloseWindow
End
EndIf
Procedure SortComboBox(BoxID)
;Sort combobox using the bubble sort
Start = ElapsedMilliseconds()
N = CountGadgetItems(BoxID)
For i = 1 To N-1 ; Loop cycles around N-1 times (because of the J+1 thing.
For J = 0 To N-2 ; -2 because of the J+1 thing and starting at 0
C$ = GetGadgetItemText(BoxID, J)
N$ = GetGadgetItemText(BoxID, J+1)
If C$ > N$
SetGadgetItemText(BoxID, J, N$)
SetGadgetItemText(BoxID, J+1, C$)
EndIf
Next
Next
Time.l = ElapsedMilliseconds()-Start
MessageRequester("Elapsed Time", Str(Time) + " ms")
EndProcedure

