Author: Tomas Rutkauskas
In the column of a TStringGrid, how do I assign as ColWidth the widest text inside
its corresponding cells?
Answer:
You measure the text using the TStringGrid's canvas:
1 2 procedure SetGridColumnWidths(Grid: TStringGrid; const Columns: arrayof Integer);
3 const4 DEFBORDER = 8;
5 var6 max, temp, i, n: Integer;
7 begin8 with Grid do9 begin10 Canvas.Font := Font;
11 for n := Low(Columns) to High(Columns) do12 begin13 max := 0;
14 for i := 0 to RowCount - 1 do15 begin16 temp := Canvas.TextWidth(Cells[Columns[n], i]) + DEFBORDER;
17 if temp > max then18 max := temp;
19 end;
20 if max > 0 then21 ColWidths[Columns[n]] := max;
22 end;
23 end;
24 end;
25 26 //Use this like:27 28 SetGridColumnWidths(stringgrid1, [1, 4]);
This would adjust the widths of columns 1 and 4 to fit the contents.