1. Home
  2. Computing & Technology
  3. Delphi Programming

How to Sort a ListView
Implementing custom sorting for a TListView component

By , About.com Guide

When you are working with a TListView component and want to sort the items based on a custom criteria, you can use the following idea...

Suppose you have assigned numbers for the TListItem Caption property and need to sort the ListView when displayed in a report-style.
To use custom sorting handle the OnCompare event. If an OnCompare event handler is assigned, AlphaSort method uses that event handler to define the sort order - call AlphaSort to sort the items.

~~~~~~~~~~~~~~~~~~~~~~~~~
procedure TForm1.ListView1Compare(
   Sender: TObject;
   Item1,
   Item2: TListItem;
   Data: Integer;
   var Compare: Integer) ;
var
   intItem1,
   intItem2: Integer;
begin
   intItem1 := StrToInt(Item1.Caption) ;
   intItem2 := StrToInt(Item2.Caption) ;

   if intItem1 < intItem2 then
     Compare := -1
   else
   if intItem1 > intItem2 then
     Compare := 1
   else // intItem1 = intItem2
     Compare := 0;
end;
~~~~~~~~~~~~~~~~~~~~~~~~~

Delphi tips navigator:
» Enabling Cassini to use Client-Side Validation in ASP.NET
« How to Enable the Refresh button on a DBNavigator for ReadOnly Datasets

More Delphi Programming Quick Tips
Explore Delphi Programming
About.com Special Features

Holiday Central

What to eat, where to go, fun things to do and how to save money on the perfect gifts. More >

Family Tech Center

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

  1. Home
  2. Computing & Technology
  3. Delphi Programming
  4. Using VCL Components
  5. TListView
  6. How to Sort a TListView Delphi component

©2009 About.com, a part of The New York Times Company.

All rights reserved.