user3193843
user3193843

Reputation: 305

Delphi XE sort listview in datetime order

I am using the following code to populate a list view with the contents of a folder on windows and IOS.

procedure TTabbedForm.btnGetQuotesClick(Sender: TObject);
var
  LList: TStringDynArray;
  i : Integer;
  LItem : TlistViewItem;
  windowsDir,AppPath : String;
begin
  ListBox1.Items.Clear;
  ListView1.Items.Clear;
{$IF DEFINED(MSWINDOWS)}
  windowsDir := TDirectory.GetCurrentDirectory;
  LList := TDirectory.GetFiles(windowsDir+'\quotes','*.txt');
  for i := 0 to Length(LList) - 1 do
  begin
    ListBox1.Items.Add(LList[i])  ;

    LItem := listView1.Items.Add;
    LItem.Text :=  LList[i];
  end;
{$ENDIF}
{$IF DEFINED(iOS) or DEFINED(ANDROID)}

  AppPath := TPath.GetDocumentsPath + PathDelim;
  LList := TDirectory.GetFiles(AppPath,'*.txt');
  for i := 0 to Length(LList) - 1 do
  begin
    ListBox1.Items.Add(LList[i])  ;
    LItem := listView1.Items.Add;
    LItem.Text :=  LList[i];
  end;
{$ENDIF}
end;

I now need to sort the list in timestamp order / ascending and descending.

Thanks in advance.

Upvotes: 1

Views: 1501

Answers (2)

Matt Allwood
Matt Allwood

Reputation: 1438

Adding to @David Hefferman's comment, you want to look at refactoring your code so that the UI-dependent code (Get file list and get file age) is separate. I'd recommend making your own function that will return an array of FileName/FileDate records which can then be consumed by the loop in the calling code.

Regarding the How To Sort - you'll need to write a CustomSort routine - have a look at these other SO questions:

how to sort in Tlistview based on subitem[x]

Sorting TListView Columns

If you don't do this then they'll either get sorted by Filename or by the DateTime field sorted as strings (i.e. it will go in order of 01/01/15 -> 11/01/15 -> 02/01/15 rather than 01/01/15 -> 02/01/15 -> 11/01/15)

Upvotes: 1

aleroot
aleroot

Reputation: 72676

There is no overloaded version of GetFiles static method that accept a sorting function as parameter, so I think that in this case the only option would be to use the FileAge ( function FileAge(const FileName: string; out FileDateTime: TDateTime) ), on each filename to get the last modified date and time of the file, and then on a second step ordering the files as you need ...

Upvotes: 0

Related Questions