ReRe: autosize column widths of Delphi StringGrid

Posted by webmaster Guido on September 08, 2005

In Reply to: Re: column widths of Delphi StringGrid posted by Lionel on September 07, 2005

: : We've recently set up a new mini-tutorial, accesible from a link on DelphiLand's home page, as well as from the Code Snips page under "StringGrid Column Widths".
: ***************************

: Thanks,
: This is what I needed to get my data to fit in the Stringgrid, I have tried it and it seems to be working OK but have not finalized it yet. I am using a button to set column width after loading a File, is this the way to do it?--or should I set the column width upon loading with out the button?

If you always want to resize the colums after loading a CSV file in Delphi, it seems better to call the resizing method automatically, without using a button (but it's very useful to have a button initially, in the debugging phase:)
For example:

  // Load a file: 
  // ...
  // Afterwards, resize the StringGrid:
  AutoSizeGrid(Grid1); 
  // And so on...

And the code for the resizing method:

procedure TForm1.AutoSizeGrid(Grid: TStringGrid);
const 
  ColWidthMin = 10;
var 
  C, R, W, ColWidthMax: integer;
begin
  for C := 0 to Grid.ColCount - 1 do begin
    ColWidthMax := ColWidthMin;
    for R := 0 to (Grid.RowCount - 1) do begin
      W := Grid1.Canvas.TextWidth(Grid.Cells[C, R]);
      if W > ColWidthMax then 
        ColWidthMax := W;
    end;
    Grid.ColWidths[C] := ColWidthMax + 5;
  end;
end;