How to Sort a ListView

By | March 17, 2011
When you are working with a TListView component and want to sort the items based on a custom criteria, you can use the following idea...

Suppose you have assigned numbers for the TListItem Caption property and need to sort the ListView when displayed in a report-style.
To use custom sorting handle the OnCompare event. If an OnCompare event handler is assigned, AlphaSort method uses that event handler to define the sort order - call AlphaSort to sort the items.

~~~~~~~~~~~~~~~~~~~~~~~~~
procedure TForm1.ListView1Compare(
   Sender: TObject;
   Item1,
   Item2: TListItem;
   Data: Integer;
   var Compare: Integer) ;
var
   intItem1,
   intItem2: Integer;
begin
   intItem1 := StrToInt(Item1.Caption) ;
   intItem2 := StrToInt(Item2.Caption) ;

   if intItem1 < intItem2 then
     Compare := -1
   else
   if intItem1 > intItem2 then
     Compare := 1
   else // intItem1 = intItem2
     Compare := 0;
end;
~~~~~~~~~~~~~~~~~~~~~~~~~