Example Delphi
Delphi Examples Collection
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.
Post Meta
-
Database, Tips and Tricks -
Comments Feed -
 
 
 
 
Nice but limited to 31 columns.
Replace lmax: array [0..30] of Integer; with lmax: array of Integer;. Add SetLength(lmax,Columns.Count - 1); just before the first for n := 0 to Columns.Count - 1 do.
Oops, submitted to soon.
Also add
DataSource.DataSet.DisableControls;
and
DataSource.DataSet.EnableControls;
to beginning and ending of the
with Grid do block
to prevent flicker/scrolling of the DBGrid.