SortGadgetItems()
Posted: Fri Mar 01, 2013 8:21 pm
Hi,
today i needed to sort some list items in a combo box and wrote this very handy procedure. You can sort ascendingly or descendingly. The selection keeps untouched and no unwanted event will be fired.
Best regards
Uwe
today i needed to sort some list items in a combo box and wrote this very handy procedure. You can sort ascendingly or descendingly. The selection keeps untouched and no unwanted event will be fired.
Code: Select all
Procedure SortGadgetItems(Gadget, Order=#PB_Sort_Ascending)
;sort gadget items
Protected n, i, j, a.s, b.s, c.s
n = CountGadgetItems(Gadget)
;remember selection
c.s = GetGadgetText(Gadget)
;sort items
For i = 0 To n - 2
a = GetGadgetItemText(Gadget, i)
For j = i + 1 To n - 1
b = GetGadgetItemText(Gadget, j)
If (Order = #PB_Sort_Ascending And b < a) Or b > a
SetGadgetItemText(Gadget, i, b)
SetGadgetItemText(Gadget, j, a)
Swap a, b
EndIf
Next
Next
;restore selection
SetGadgetText(Gadget, c)
EndProcedure
If OpenWindow(0, 0, 0, 400, 300, "SortGadgetItems-Test", #PB_Window_SystemMenu | #PB_Window_ScreenCentered)
ComboBoxGadget(0, 10, 10, 200, 30)
AddGadgetItem(0, -1, "One")
AddGadgetItem(0, -1, "Two")
AddGadgetItem(0, -1, "Three")
AddGadgetItem(0, -1, "Four")
AddGadgetItem(0, -1, "Five")
ButtonGadget(1, 10, 50, 200, 30, "Sort")
Repeat
Select WaitWindowEvent()
Case #PB_Event_CloseWindow
Break
Case #PB_Event_Gadget
If EventGadget() = 1
SortGadgetItems(0)
EndIf
EndSelect
ForEver
EndIf
Uwe