uses
Math;
function DBGridRecordSize(mColumn: TColumn): Boolean;
begin
Result := False;
if not Assigned(mColumn.Field) then
Exit;
mColumn.Field.Tag := Max(mColumn.Field.Tag, TDBGrid(mColumn.Grid).Canvas.TextWidth(mColumn.Field.DisplayText));
Result := True;
end;
function DBGridAutoSize(mDBGrid: TDBGrid; mOffset: Integer = 5): Boolean;
var
I: Integer;
begin
Result := False;
if not Assigned(mDBGrid) then
Exit;
if not Assigned(mDBGrid.DataSource) then
Exit;
if not Assigned(mDBGrid.DataSource.DataSet) then
Exit;
if not mDBGrid.DataSource.DataSet.Active then
Exit;
for I := 0 to mDBGrid.Columns.Count - 1 do
begin
if not mDBGrid.Columns[I].Visible then
Continue;
if Assigned(mDBGrid.Columns[I].Field) then
mDBGrid.Columns[I].Width := Max(mDBGrid.Columns[I].Field.Tag,
mDBGrid.Canvas.TextWidth(mDBGrid.Columns[I].Title.Caption)) + mOffset
else
mDBGrid.Columns[I].Width := mDBGrid.Canvas.TextWidth(mDBGrid.Columns[I].Title.Caption) + mOffset;
mDBGrid.Refresh;
end;
Result := True;
end;
procedure TForm1.DBGrid1DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn;
State: TGridDrawState);
begin
DBGridRecordSize(Column);
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
DBGridAutoSize(DBGrid1);
end;