JakeSays
JakeSays

Reputation: 2068

Sorting TListView Columns

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

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

Upvotes: 4

Views: 10062

Answers (1)

David Heffernan
David Heffernan

Reputation: 613461

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.

Upvotes: 7

Related Questions