Mega Code Archive

 
Categories / Delphi / VCL
 

Optimal Cell Width of a StringGrid

Title: Optimal Cell Width of a StringGrid Question: How to set the columns width of a StringGrid without truncate any text Answer: After filling your StringGrid with text strings call the procedure SetOptimalGridCellWidth thanks to William Sorensen for some improvements on the code. -----------snip------------------------------------------------- (* $Header$ Module Name : General\BSGrids.pas Main Program : Several. Description : StringGrid support functions. 03/21/2000 enhanced by William Sorensen *) unit BSGrids; interface uses Grids; type TExcludeColumns = set of 0..255; procedure SetOptimalGridCellWidth(sg: TStringGrid; ExcludeColumns: TExcludeColumns); // Sets column widths of a StringGrid to avoid truncation of text. // Fill grid with desired text strings first. // If a column contains no text, DefaultColWidth will be used. // Pass [] for ExcludeColumns to process all columns, including Fixed. // Columns whose numbers (0-based) are specified in ExcludeColumns will not // have their widths adjusted. implementation uses Math; // we need the Max function procedure SetOptimalGridCellWidth(sg: TStringGrid; ExcludeColumns: TExcludeColumns); var i : Integer; j : Integer; max_width : Integer; begin with sg do begin // If the grid's Paint method hasn't been called yet, // the grid's canvas won't use the right font for TextWidth. // (TCustomGrid.Paint normally sets this, under DrawCells.) Canvas.Font.Assign(Font); for i := 0 to (ColCount - 1) do begin if i in ExcludeColumns then Continue; max_width := 0; // Search for the maximal Text width of the current column. for j := 0 to (RowCount - 1) do max_width := Math.Max(max_width,Canvas.TextWidth(Cells[i,j])); // The hardcode of 4 is based on twice the offset from the left // margin in TStringGrid.DrawCell. GridLineWidth is not relevant. if max_width 0 then ColWidths[i] := max_width + 4 else ColWidths[i] := DefaultColWidth; end; { for } end; end; end.