Today, Delphi is one of the popular desktop programming tool. There are thousand even million programmer in this world using delphi as their favorit tool. This site try to collect the examples, tips and tricks of Delphi programming. We collect, test them and redistribute the collection of delphi programming for you.

Autosize DBGrid

Author: admin | Category: Database, Tips and Tricks

//This is how we can set our DbGrid column width match to it's longest record
 
unit Unit1;
 
interface
 
uses
  XPMAN, Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls, Grids, DBGrids, ExtCtrls, DB, ADODB;
 
type
  TForm1 = class(TForm)
    DataSource1: TDataSource;
    ADOTable1: TADOTable;
    Panel1: TPanel;
    Panel2: TPanel;
    DBGrid1: TDBGrid;
    Button1: TButton;
    procedure FormCreate(Sender: TObject);
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;
 
var
  Form1: TForm1;
 
implementation
 
{$R *.dfm}
 
procedure SetGridColumnWidths(Grid: Tdbgrid);
const
  DEFBORDER = 10;
var
  temp, n: Integer;
  lmax: array [0..30] of Integer;
begin
  with Grid do
  begin
    Canvas.Font := Font;
    for n := 0 to Columns.Count - 1 do
      lmax[n] := Canvas.TextWidth(Fields[n].FieldName) + DEFBORDER;
    grid.DataSource.DataSet.First;
    while not grid.DataSource.DataSet.EOF do
    begin
      for n := 0 to Columns.Count - 1 do
      begin
        temp := Canvas.TextWidth(trim(Columns[n].Field.DisplayText)) + DEFBORDER;
        if temp > lmax[n] then lmax[n] := temp;
      end; {for}
      grid.DataSource.DataSet.Next;
    end;
    grid.DataSource.DataSet.First;
    for n := 0 to Columns.Count - 1 do
      if lmax[n] > 0 then
        Columns[n].Width := lmax[n];
  end;
end; {SetGridColumnWidths  }
 
procedure TForm1.FormCreate(Sender: TObject);
begin
   ADOTable1.Active:=True;
end;
 
procedure TForm1.Button1Click(Sender: TObject);
begin
   SetGridColumnWidths(DBGrid1);
end;
 
end.

Tags: ,