Sorting a TListView by the column clicked by the user

How to sort a ListView in ascending or descending order by a given column?

Sorting a TListView by the column clicked by the user

We want the following behaviour for a ListView:

  • When the user clicks on a column header, the ListView should be sorted by that column

  • The initial sort order should be ascending. If the user clicks on the same column again, the sort order should be toggled. If the user clicks on another column, the sort order of the new column should be the same as the last sorted column.

For the implementation we need two variables to hold the last column clicked by the user and the current sort order:


    LastSortedColumn: integer;

    Ascending: boolean;

We can initialize them when the form is created:

procedure TForm1.FormCreate(Sender: TObject);


    LastSortedColumn := -1;

    Ascending := True;


In the ColumnClick event of the ListView we determine the sort order and perform the sort:

procedure TForm1.ListView1ColumnClick(Sender: TObject;

    Column: TListColumn);


    if Column.Index = LastSortedColumn then

      Ascending := not Ascending


      LastSortedColumn := Column.Index;

    TListView(Sender).CustomSort(@SortByColumn, Column.Index);


SortByColumn is a function that should be previously declared and is the function used by CustomSort to compare two items. The value passed to the Data parameter of CustomSort will be passed as the Data parameter to SortByColumn and we use it for the sort column:

function SortByColumn(Item1, Item2: TListItem; Data: integer):

    integer; stdcall;


    if Data = 0 then

      Result := AnsiCompareText(Item1.Caption, Item2.Caption)


      Result := AnsiCompareText(Item1.SubItems[Data-1],


    if not Ascending then Result := -Result;


You can find the full source code of this article in the archive that accompanies the Pascal Newsletter #25


Share this article!

Follow us!

Find more helpful articles: