Saturday, June 4, 2022

Delphi Tip of the Day - Auto Adjust FMX StringGrid Column Widths

 I've been playing around with the FMX StringGrid for the past three weeks. And I thought... 

"Wouldn't it be nice if there was a way to automatically resize the column widths based on the values in each of the columns. Just like the way Excel works when you highlight the entire sheet and double-click the thin line between two columns."

In today's Delphi tip of the day I present a simple routine that evaluates the data in each of the column headings and the columns of each row to determine how wide to make the cells. And the best part is, it automatically adjusts all the columns widths in one go.

"Just like the way Excel works..."


It's fairly straight forward using two for loops. It loops through each column looking at every row and determining the width that column needs to be based on the data in each cell.

procedure AutoAdjustColumnWidths(const Grid : TStringGrid);
var
  col : Integer;  //Grid Column
  w   : single;   //New Width
  s   : string;   //Grid Column value
  l   : Integer;  //Lenght of Grid Column value
  row : Integer;  //Grid Row
  r   : Single;   //Result of TextWidth calculation
begin
  for col := 0 to Grid.ColumnCount-1 do
  begin
    w := 0;
    s := Grid.ColumnByIndex(col).Header;
    l := length(s);
    w := Grid.TextWidthToColWidth(l,s) * 1.05; //add a little padding
    for row := 0 to Grid.RowCount-1 do
    begin
      s := Grid.Cells[col,row];
      l := length(s);
      r := Grid.TextWidthToColWidth(l,s) * 1.05; //add a little padding
      if r > w then
        w := r;
    end;
    Grid.Columns[col].Width := w;
  end;
end;

I'm sure this can be improved upon so it only evaluates the first 50 or 100 rows. I'll leave that up to you to figure out.

Enjoy,
Gunny Mike
https://zilchworks.com