Author: Tomas Rutkauskas
How to sort a TListView on a column header click
Answer:
In the object inspector, I have set the ListView's SortType = stText.
1 {Private Declarations}2 SortColumn: Integer;
3 SortDescending: Boolean;
4 5 procedure Sort(Column: Integer);
6 7 procedure TfrmMain.ListViewColumnClick(Sender: TObject; Column: TListColumn);
8 begin9 Sort(Column.Index);
10 end;
11 12 procedure TfrmMain.Sort(Column: Integer);
13 begin14 if SortColumn = Column then15 SortDescending := not SortDescending
16 else17 begin18 SortDescending := False;
19 SortColumn := Column;
20 end;
21 lsvPlayerPages.AlphaSort;
22 end;
23 24 procedure TfrmMain.ListViewCompare(Sender: TObject; Item1, Item2: TListItem;
25 Data: Integer; var Compare: Integer);
26 begin27 if SortColumn = 0 then28 Compare := CompareStr(Item1.Caption, Item2.Caption)
29 else30 Compare := CompareStr(Item1.SubItems[Pred(SortColumn)],
31 Item2.SubItems[Pred(SortColumn)]);
32 if SortDescending then33 Compare := -Compare;
34 end;
I have made a separate sort procedure to be able to sort from different commands (e.g. from a menu). The code also sorts descending if a column header is clicked a second time (as Windows Explorer does).