Sort ListView by clicking on columns

First of all, set ListView to vsReport style and fill in some data. OnColumnClick and OnCompare events will do the rest.
We need two more global variables – Descending (boolean type) to store the order of sorting, and SortedColumn to keep the number of column by which is the ListView sorted.

private
{ Private declarations }
Descending: Boolean;
SortedColumn: Integer;

procedure TForm1.ListView1ColumnClick(Sender: TObject;  Column: TListColumn);
begin
TListView(Sender).SortType := stNone;
if Column.Index<>SortedColumn then
begin
SortedColumn := Column.Index;
Descending := False;
end
else
Descending := not Descending;
TListView(Sender).SortType := stText;
end;

procedure TForm1.ListView1Compare(Sender: TObject; Item1, Item2: TListItem; Data: Integer; var Compare: Integer);
begin
if SortedColumn = 0 then Compare := CompareText(Item1.Caption, Item2.Caption)
else
if SortedColumn <> 0 then Compare := CompareText(Item1.SubItems[SortedColumn-1], Item2.SubItems[SortedColumn-1]);
if Descending then Compare := -Compare;
end;

SortType parameter could have these values:

  • stNone
  • stData
  • stText
  • stBoth

Leave a Reply