Author: Tomas Rutkauskas How to sort a TCheckListBox without loosing the check state Answer: Sorting without loosing the check state is a bit of a challenge, but it can be done. The code below has only been superficially tested: 1 { ... } 2 type 3 TItemState = class 4 public 5 Data: TObject; 6 Checked: Boolean; 7 constructor Create(aData: TObject; aChecked: Boolean); 8 end; 9 10 constructor TItemState.Create(aData: TObject; aChecked: Boolean); 11 begin 12 inherited Create; 13 Data := aData; 14 Checked := aChecked; 15 end; 16 17 procedure CustomSortChecklist(aList: TChecklistbox; Compare: TStringListSortCompare 18 = nil); 19 var 20 sl: TStringlist; 21 i: Integer; 22 stateobj: TItemState; 23 begin 24 Assert(Assigned(aList), 'CustomSortChecklist: no list to sort.'); 25 sl := TStringlist.Create; 26 try 27 sl.Assign(aList.Items); 28 for i := 0 to sl.Count - 1 do 29 sl.Objects[i] := TItemState.Create(sl.Objects[i], aList.Checked[i]); 30 if Assigned(Compare) then 31 sl.CustomSort(Compare) 32 else 33 sl.Sort; 34 alist.Items.BeginUpdate; 35 try 36 aList.Clear; 37 for i := 0 to sl.Count - 1 do 38 begin 39 stateobj := sl.Objects[i] as TItemState; 40 aList.Items.AddObject(sl[i], stateobj.Data); 41 aList.Checked[i] := stateobj.Checked; 42 end; 43 finally 44 aList.Items.EndUpdate; 45 end; 46 finally 47 for i := 0 to sl.Count - 1 do 48 if Assigned(sl.Objects[i]) and (sl.Objects[i] is TItemState) then 49 sl.Objects[i].Free; 50 sl.free; 51 end; 52 end; 53 54 procedure TForm1.Button1Click(Sender: TObject); 55 begin 56 CustomSortChecklist(checklistbox1); 57 end; 58 59 function ReverseSort(List: TStringList; Index1, Index2: Integer): Integer; 60 begin 61 result := AnsiCompareText(list[index2], list[index1]); 62 end; 63 64 procedure TForm1.Button2Click(Sender: TObject); 65 begin 66 CustomSortChecklist(checklistbox1, Reversesort); 67 end;