whats new ¦  programming tips ¦  indy articles ¦  intraweb articles ¦  informations ¦  links ¦  interviews
 misc ¦  tutorials ¦  Add&Win Game

Tips (1541)

Database (90)
Files (137)
Forms (107)
Graphic (114)
IDE (21)
Indy (5)
Internet / LAN (130)
IntraWeb (0)
Math (76)
Misc (126)
Multimedia (45)
Objects/
ActiveX (51)

OpenTools API (3)
Printing (35)
Strings (83)
System (266)
VCL (242)

Top15

Tips sort by
component


Search Tip

Add new Tip

Add&Win Game

Advertising

47 Visitors Online


 
...autosize a StringGrid-Column to fit its content?
Autor: Thomas Stutz
[ Print tip ]  

Tip Rating (17):  
     


{1.}

procedure SetGridColumnWidths(Grid: TStringGrid;
  const Columns: array of Integer);
{
  When you double-Click on a Column-Header the Column
  autosizes to fit its content

  Bei Doppelklick auf eine fixierte Spalte passt sich
  die Spaltenbreite der Textgrösse an
}

  
procedure AutoSizeGridColumn(Grid: TStringGrid; column, min, max: Integer);
    { Set for max and min some minimal/maximial Values}
    { Bei max and min kann eine Minimal- resp. Maximalbreite angegeben werden}
  
var
    
i: Integer;
    temp: Integer;
    tempmax: Integer;
  begin
    
tempmax := 0;
    for i := 0 to (Grid.RowCount - 1) do
    begin
      
temp := Grid.Canvas.TextWidth(Grid.cells[column, i]);
      if temp > tempmax then tempmax := temp;
      if tempmax > max then
      begin
        
tempmax := max;
        break;
      end;
    end;
    if tempmax < min then tempmax := min;
    Grid.ColWidths[column] := tempmax + Grid.GridLineWidth + 3;
  end;

  procedure TForm1.StringGrid1DblClick(Sender: TObject);
  var
    
P: TPoint;
    iColumn, iRow: Longint;
  begin
    
GetCursorPos(P);
    with StringGrid1 do
    begin
      
P := ScreenToClient(P);
      MouseToCell(P.X, P.Y, iColumn, iRow);
      if P.Y < DefaultRowHeight then
        
AutoSizeGridColumn(StringGrid1, iColumn, 40, 100);
    end;
  end;

  {************************************************}

  {2.}

  
procedure TForm1.Button1Click(Sender: TObject);
  { by P. Below }
  
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{ For }
        
if max > 0 then
          
ColWidths[Columns[n]] := max;
      end{ For }
    
end{ With }
  
end{SetGridColumnWidths  }

 

Rate this tip:

poor
very good


Copyright © by SwissDelphiCenter.ch
All trademarks are the sole property of their respective owners