I am trying to make a frame with a DBGrid
that will serve for more than 10 tables with half of its fields as defaults, and other fields exclusive for each table
EDITED:
My first code was about fit the columns inside the grid with, with this new code, AutoSizeColumns reads the records to calc the width of each column until MaxRows or Dataset.Eof:
class function TDBGridHelper.AutoSizeColumns(DBGrid: TDBGrid; const MaxRows: Integer = 25): Integer;
var
DataSet: TDataSet;
Bookmark: TBookmark;
Count, I: Integer;
ColumnsWidth: array of Integer;
begin
SetLength(ColumnsWidth, DBGrid.Columns.Count);
for I := 0 to DBGrid.Columns.Count - 1 do
if DBGrid.Columns[I].Visible then
ColumnsWidth[I] := DBGrid.Canvas.TextWidth(DBGrid.Columns[I].Title.Caption + ' ')
else
ColumnsWidth[I] := 0;
if DBGrid.DataSource <> nil then
DataSet := DBGrid.DataSource.DataSet
else
DataSet := nil;
if (DataSet <> nil) and DataSet.Active then
begin
Bookmark := DataSet.GetBookmark;
DataSet.DisableControls;
try
Count := 0;
DataSet.First;
while not DataSet.Eof and (Count < MaxRows) do
begin
for I := 0 to DBGrid.Columns.Count - 1 do
if DBGrid.Columns[I].Visible then
ColumnsWidth[I] := Max(ColumnsWidth[I], DBGrid.Canvas.TextWidth(
DBGrid.Columns[I].Field.Text));
Inc(Count);
DataSet.Next;
end;
finally
DataSet.GotoBookmark(Bookmark);
DataSet.FreeBookmark(Bookmark);
DataSet.EnableControls;
end;
end;
Count := 0;
for I := 0 to DBGrid.Columns.Count - 1 do
if DBGrid.Columns[I].Visible then
begin
DBGrid.Columns[I].Width := ColumnsWidth[I];
Inc(Count, ColumnsWidth[I]);
end;
Result := Count - DBGrid.ClientWidth;
end;
I call it in the DataSet.AfterOpen event:
TGridHelper.AutoSizeColumns(MyDBGrid);
For each column you want to be auto sized set the property SizePriority=1
and for fixed columns set SizePriority=0
, in your case only the last column will be auto sized.
Then set property grid.AutoFillColumns=true
and that should do it.