list all files from a directory in a string grid with delphi

三世轮回 提交于 2020-01-06 02:59:10

问题


I am working with Delphi 7 and I would like to list all the files in a given directory in a string grid (one file per row and all in 1 column). I have searched for about an hour now and cannot find any examples on how to do this so any help you can provide would be appreciated.


回答1:


This will fill a TStrings descendant (eg., TStringList, TMemo.Lihes, and so forth) with all of the files in a specified folder:

function  GetFiles(const StartDir: String; const List: TStrings): Boolean;
var
  SRec: TSearchRec;
  Res: Integer;
begin
  if not Assigned(List) then
  begin
    Result := False;
    Exit;
  end;
  Res := FindFirst(StartDir + '*.*', faAnyfile, SRec );
  if Res = 0 then
  try
    while res = 0 do
    begin
      if (SRec.Attr and faDirectory <> faDirectory) then
        // If you want filename only, remove "StartDir +" 
        // from next line
        List.Add( StartDir + SRec.Name );
      Res := FindNext(SRec);
    end;
  finally
    FindClose(SRec)
  end;
  Result := (List.Count > 0);
end;

Use it like this to populate your TStringGrid (Grid in the code below - I added code to auto-size the column based on the length of the longest filename):

var
  SL: TStringList;
  i: Integer;
  MaxWidth, CurrWidth: Integer;
const
  Padding = 10;
begin
  SL := TStringList.Create;
  try
    if GetFiles('C:\Temp\', SL) then
    begin
      MaxWidth := Grid.ColWidths[0];
      for i := 0 to SL.Count - 1 do
      begin
        CurrWidth := Grid.Canvas.TextWidth(SL[i]);
        if CurrWidth > MaxWidth then
          MaxWidth := CurrWidth;
        // Populates first column in stringgrid.
        Grid.RowCount := Grid.RowCount + 1;
        Grid.Cells[0, Grid.RowCount - 1] := SL[i];
      end;
      Grid.ColWidths[0] := MaxWidth + Padding;
    end;
  finally
    SL.Free;
  end;
end;

Note that this code requires the path to include the trailing backslash after the folder name; you can modify it easily to automatically add it if needed, or to accept both a folder name and a file mask to include only certain files.




回答2:


  1. Use SysUtil.FindFirst/FindNext/FindClose to get files

  2. Simply insert the string at desired row/column. Increase "RowCount" as needed:

    • Add Rows

    • Insert/Delete rows

    • Lazarus String Grids reference (good info, but significant differences from Delphi)



来源:https://stackoverflow.com/questions/11489680/list-all-files-from-a-directory-in-a-string-grid-with-delphi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!