2005. november 18., péntek

Sort a TListView on a column header click


Problem/Question/Abstract:

How to sort a TListView on a column header click

Answer:

In the object inspector, I have set the ListView's SortType = stText.

{Private Declarations}
SortColumn: Integer;
SortDescending: Boolean;

procedure Sort(Column: Integer);

procedure TfrmMain.ListViewColumnClick(Sender: TObject; Column: TListColumn);
begin
  Sort(Column.Index);
end;

procedure TfrmMain.Sort(Column: Integer);
begin
  if SortColumn = Column then
    SortDescending := not SortDescending
  else
  begin
    SortDescending := False;
    SortColumn := Column;
  end;
  lsvPlayerPages.AlphaSort;
end;

procedure TfrmMain.ListViewCompare(Sender: TObject; Item1, Item2: TListItem;
  Data: Integer; var Compare: Integer);
begin
  if SortColumn = 0 then
    Compare := CompareStr(Item1.Caption, Item2.Caption)
  else
    Compare := CompareStr(Item1.SubItems[Pred(SortColumn)],
      Item2.SubItems[Pred(SortColumn)]);
  if SortDescending then
    Compare := -Compare;
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).

Nincsenek megjegyzések:

Megjegyzés küldése