4

I have a TListview with 4 columns (which are all strings of course) however, I store data in them as such:

  • Caption: any string
  • SubItems[0]: integer, e.g. '5016'
  • SubItems[1]: date, e.g. '03/22/13'
  • Subitems[2]: any string

I use the following code to sort when user clicks a column header

I was looking at this post "how to sort in Tlistview based on subitem[x]" but I can't figure out how to take the different column types into consideration.

procedure TfrmFind.lvwTagsColumnClick(Sender: TObject; Column: TListColumn);
begin
 ColumnToSort := Column.Index;
 (Sender as TCustomListView).AlphaSort;
end;

procedure TfrmFind.lvwTagsCompare(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;

How can I take into consideration of the Integer and Date columns so they are not sorted as strings?

Thanks

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
JakeSays
  • 2,048
  • 8
  • 29
  • 43

1 Answers1

7

If you have two strings that contain integers and you wish to compare as integers then convert them from text to integer, and compare numerically.

function CompareTextAsInteger(const s1, s2: string): Integer;
begin
  Result := CompareValue(StrToInt(s1), StrToInt(s2));
end;

And similarly for dates. Convert them from text to numeric values, for example TDateTime values. And then compare numerically.

function CompareTextAsDateTime(const s1, s2: string): Integer;
begin
  Result := CompareDateTime(StrToDateTime(s1), StrToDateTime(s2));
end;

Exactly how you implement this latter function depends on how you want to convert from text to numeric representation of date/time.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
  • David, how do I switch between the two based on column index? Uisnf the column click event – JakeSays Mar 22 '13 at 16:32
  • Well, the `OnColumnClick` tells you which column has been clicked. At which point you presumably know what is in that column and can decide from there. – David Heffernan Mar 22 '13 at 16:55
  • `CompareValue` is in `Math` and `CompareDateTime` is in `DateUtils`. That information is available in the help: http://docwiki.embarcadero.com/RADStudio/XE3/en/Main_Page Just type the function name into the search box – David Heffernan Mar 22 '13 at 16:57
  • Compare := CompareTextAsInteger(Item1.subitems[0],Item2.subitems[0]) – JakeSays Mar 22 '13 at 17:06