TListViewOnColumnClick (Delphi)
Description
This example shows how to use the OnColumnClick and OnCompare events of a list view to let users sort the columns in a report-style list view by clicking the column headers. This requires a global variable to keep track of the column that was clicked. The OnColumnClick event handler sets the global variable to indicate the column to sort and calls AlphaSort.
Code
var ColumnToSort: Integer;
procedure TForm1.FormCreate(Sender: TObject);
var
I: Integer;
ListItem: TListItem;
NewColumn: TListColumn;
const
imagenames: Array[0..2] of string = ('C++ Image', 'Borland Image', 'Delphi Image');
begin
Col2Array[0]:= 'Documentation for the C++ icon.';
Col2Array[1]:= 'Borland icon.';
Col2Array[2]:= 'Delphi icon.';
// Create a ListView item for each image in the ImageList.
with ListView1 do
begin
SmallImages := ImageList1;
LargeImages := ImageList1;
for I := 0 to ImageList1.Count - 1 do
begin
ListItem := Items.Add;
Listitem.Caption := imagenames[I];
ListItem.ImageIndex := I;
Listitem.SubItems.Add(Col2Array[I]);
end;
// Create two columns to show during viewing as vsReport.
NewColumn := Columns.Add;
NewColumn.Caption := 'Column 1';
NewColumn.Width := 200;
NewColumn := Columns.Add;
NewColumn.Caption := 'Column 2';
NewColumn.Width := 200;
ListView1.ViewStyle := vsReport;
end;
end;
procedure TForm1.ListView1ColumnClick(Sender: TObject; Column: TListColumn);
begin
ColumnToSort := Column.Index;
(Sender as TCustomListView).AlphaSort;
end;
{
The OnCompare event handler causes the
list view to sort on the selected column.
procedure TForm1.ListView1Compare(Sender: TObject; Item1, Item2: TListItem; Data: Integer; var Compare: Integer);
var
ix: Integer;
begin
if ColumnToSort = 0 then
Compare := CompareText(Item1.Caption,Item2.Caption)
else begin
ix := ColumnToSort - 1;
Compare := CompareText(Item1.SubItems[ix],Item2.SubItems[ix]);
end;
end;
{
Note: This OnCompare event handler uses the global
CompareText function. An application may want to use
AnsiCompareText, CompareStr, or AnsiCompareStr instead,
depending on whether the comparison should be case-sensitive
and whether the locale should be considered.
Uses
- Vcl.ComCtrls.TCustomListView.OnColumnClick ( fr | de | ja )
- Vcl.ComCtrls.TCustomListView.AlphaSort ( fr | de | ja )
- Vcl.ComCtrls.TCustomListView.OnCompare ( fr | de | ja )
- System.SysUtils.CompareText ( fr | de | ja )
- System.AnsiStrings.CompareText ( fr | de | ja )
- Vcl.ImgList.TCustomImageList.GetCount ( fr | de | ja )
- Vcl.ComCtrls.TListItem.Caption ( fr | de | ja )