Author: Tomas Rutkauskas
I created a component TMyCheckListBox which inherited from TCheckListBox, and I
want to sort the list of items in numeric not alphabetic order. Although I set the
Sorted property to True, I cannot sort it in the way I want. I need to have a
numeric sort with the Sorted property set to True.
Answer:
The Sorted property calls the built-in capability of the underlying windows control
to sort itself alphabetically. In case you need to perform a custom sorting, just
turn the Sorted property off, and do the sorting by using TStringList CustomSort
method. Below is the sequence of possible steps
Assign listbox's items to the string list. Perform custom sorting by calling the
CustomSort method. You should pass a function that compares two strings in the
string list as parameter (see example below for details). Move items back to the
listbox. Here's an example. It resorts the list's content in custom order:
1 {This function sorts items in the list}2 3 function CompareStrings(List: TStringList; Index1, Index2: Integer): Integer;
4 var5 XInt1, XInt2: integer;
6 begin7 try8 XInt1 := strToInt(List[Index1]);
9 XInt2 := strToInt(List[Index2]);
10 except11 XInt1 := 0;
12 XInt2 := 0;
13 end;
14 Result: = XInt1 - XInt2;
15 end;
16 17 procedure TForm1.SpeedButton5Click(Sender: TObject);
18 var19 XList: TStringList;
20 begin21 XList := TStringList.Create;
22 CheckListBox1.Items.BeginUpdate;
23 try24 XList.Assign(CheckListBox1.Items);
25 XList.CustomSort(CompareStrings);
26 CheckListBox1.Items.Assign(XList);
27 finally28 XList.Free;
29 CheckListBox1.Items.EndUpdate;
30 end;
31 end;