首页  编辑  

StringGrid的AutoSize

Tags: /超级猛料/VCL/Grid控件/   Date Created:

...autosize a StringGrid-Column to fit its content?

{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  }