How to show sort arrow in TListView column?

There is an arrow in Windows Explorer that indicates in which column the list view (in the presentation style) is sorted by and in which direction (ASC versus DESC).

Is it possible to display such an arrow indicating a view on a TListView in Delphi?

+6
source share
2 answers

Here is some simple code to mark the header column as sorted in ascending order:

 uses Winapi.CommCtrl; var Header: HWND; Item: THDItem; begin Header := ListView_GetHeader(ListView1.Handle); ZeroMemory(@Item, SizeOf(Item)); Item.Mask := HDI_FORMAT; Header_GetItem(Header, 0, Item); Item.fmt := Item.fmt and not (HDF_SORTUP or HDF_SORTDOWN);//remove both flags Item.fmt := Item.fmt or HDF_SORTUP;//include the sort ascending flag Header_SetItem(Header, 0, Item); end; 

I skipped error checking for simplicity. If you want the arrow to be in the opposite direction, I am sure that you can decide how to change the logic.

The key issue of MSDN is that for HDITEM struct.

+16
source

You can easily extend this code to work for all columns in a ListView; Declare two variables (in the private section of the form):

ColumnToSort: Integer; Climb: Boolean;

Initialize them in a FormCreate procedure using 0 and True.

 procedure TForm1.ListView1ColumnClick(Sender: TObject; Column: ListColumn); var Header: HWND; Item: THDItem; begin Header := ListView_GetHeader(ListView1.Handle); ZeroMemory(@Item, SizeOf(Item)); Item.Mask := HDI_FORMAT; // Clear the previous arrow Header_GetItem(Header, ColumnToSort, Item); Item.fmt := Item.fmt and not (HDF_SORTUP or HDF_SORTDOWN);//remove both flags Header_SetItem(Header, ColumnToSort, Item); if Column.Index = ColumnToSort then Ascending := not Ascending else ColumnToSort := Column.Index; // Get the new column Header_GetItem(Header, ColumnToSort, Item); Item.fmt := Item.fmt and not (HDF_SORTUP or HDF_SORTDOWN);//remove both flags if Ascending then Item.fmt := Item.fmt or HDF_SORTUP//include the sort ascending flag else Item.fmt := Item.fmt or HDF_SORTDOWN;//include the sort descending flag Header_SetItem(Header, ColumnToSort, Item); with ListView1 do begin Items.BeginUpdate; AlphaSort; Items.EndUpdate; end; end; 

Of course, you will need to provide your own OnCompare function to actually sort the columns. This code displays the sort arrow in the column header with a click.

+2
source

All Articles