Adjust the column width in a TStringGrid to fit the widest text in a cell (Views: 713)
Problem/Question/Abstract: 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: procedure SetGridColumnWidths(Grid: TStringGrid; const Columns: array of Integer); const DEFBORDER = 8; var max, temp, i, n: Integer; begin with Grid do begin Canvas.Font := Font; for n := Low(Columns) to High(Columns) do begin max := 0; for i := 0 to RowCount - 1 do begin temp := Canvas.TextWidth(Cells[Columns[n], i]) + DEFBORDER; if temp > max then max := temp; end; if max > 0 then ColWidths[Columns[n]] := max; end; end; end; Use this like: SetGridColumnWidths(stringgrid1, [1, 4]); This would adjust the widths of columns 1 and 4 to fit the contents. |