How to automatically adjust the size of DBGrid columns?

Problem: How to occupy all the available space in the DBGrid?
Often, when we maximize a screen, there is a blank space if useful,
other times we don’t want the Grid to be scrolled.
Therefore, it is necessary a way to automatically size the columns.
Fortunately, there is a solution that is easy to implement!
Let’s go to the code:
procedure DimensionarGrid(dbg: TDBGrid); type TArray = Array of Integer; procedure AjustarColumns(Swidth, TSize: Integer; Asize: TArray); var idx: Integer; begin if TSize = 0 then begin TSize := dbg.Columns.count; for idx := 0 to dbg.Columns.count - 1 do dbg.Columns[idx].Width := (dbg.Width - dbg.Canvas.TextWidth('AAAAAA') ) div TSize end else for idx := 0 to dbg.Columns.count - 1 do dbg.Columns[idx].Width := dbg.Columns[idx].Width + (Swidth * Asize[idx] div TSize); end; var idx, Twidth, TSize, Swidth: Integer; AWidth: TArray; Asize: TArray; NomeColuna: String; begin SetLength(AWidth, dbg.Columns.count); SetLength(Asize, dbg.Columns.count); Twidth := 0; TSize := 0; for idx := 0 to dbg.Columns.count - 1 do begin NomeColuna := dbg.Columns[idx].Title.Caption; dbg.Columns[idx].Width := dbg.Canvas.TextWidth (dbg.Columns[idx].Title.Caption + 'A'); AWidth[idx] := dbg.Columns[idx].Width; Twidth := Twidth + AWidth[idx]; if Assigned(dbg.Columns[idx].Field) then Asize[idx] := dbg.Columns[idx].Field.Size else Asize[idx] := 1; TSize := TSize + Asize[idx]; end; if TDBGridOption.dgColLines in dbg.Options then Twidth := Twidth + dbg.Columns.count; // add the width of the indicated column of the cursor if TDBGridOption . dgIndicator in dbg . Options then Twidth : = Twidth + IndicatorWidth ; Swidth := dbg.ClientWidth - Twidth; AjustarColumns(Swidth, TSize, Asize); end;
See how easy it is to use the procedure:
In the OnResize event of your form, leave as shown in the example below
procedure TForm1.FormResize(Sender: TObject); begin // Just inform your DBgrid DimensionarGrid ( GridProdutos ) ; end ;