This seems to work (maybe more can be optimized):
type TCustomDBGridHack = class(TCustomDBGrid); procedure SetVisibleRows(DBGrid: TCustomDBGrid; VisibleRows: Integer); var TitleHeight, RowHeight: Integer; begin with TCustomDBGridHack(DBGrid) do begin if dgTitles in Options then begin TitleHeight := RowHeights[0] + GridLineWidth; RowHeight := RowHeights[1] + GridLineWidth; end else begin TitleHeight := 0; RowHeight := RowHeights[0] + GridLineWidth; end; end; DBGrid.ClientHeight := TitleHeight + (RowHeight * VisibleRows) + 1; end;
Or using TGridDrawInfo , as suggested by @nil. It gives more accurate results (I changed it a bit):
procedure SetVisibleRows(DBGrid: TCustomDBGrid; VisibleRows: Integer); var DrawInfo: TGridDrawInfo; TitleHeight, RowHeight: Integer; begin with TCustomDBGridHack(DBGrid) do begin CalcDrawInfo(DrawInfo); TitleHeight := DrawInfo.Vert.FixedBoundary; RowHeight := RowHeights[DrawInfo.Vert.FirstGridCell] + DrawInfo.Vert.EffectiveLineWidth; end; DBGrid.ClientHeight := TitleHeight + (RowHeight * VisibleRows) + 1; end;
As @nil already mentioned, RowHeight can also be calculated using:
RowHeight := DrawInfo.Vert.GetExtent(DrawInfo.Vert.FirstGridCell) + DrawInfo.Vert.EffectiveLineWidth;
I did not notice any difference. (should be further explored).
The above can be further improved to improve TDBGrid scroll settings:
procedure SetVisibleRows(DBGrid: TCustomDBGrid; VisibleRows: Integer); var DrawInfo: TGridDrawInfo; TitleHeight, RowHeight: Integer; HasActiveDataSet: Boolean; begin if VisibleRows < 0 then VisibleRows := 0; HasActiveDataSet := Assigned(DBGrid.DataSource) and Assigned(DBGrid.DataSource.DataSet) and DBGrid.DataSource.DataSet.Active; if HasActiveDataSet then DBGrid.DataSource.DataSet.DisableControls; try with TCustomDBGridHack(DBGrid) do begin CalcDrawInfo(DrawInfo); TitleHeight := DrawInfo.Vert.FixedBoundary; RowHeight := RowHeights[DrawInfo.Vert.FirstGridCell] + DrawInfo.Vert.EffectiveLineWidth; end; DBGrid.ClientHeight := TitleHeight + (RowHeight * VisibleRows) + 1; finally if HasActiveDataSet then DBGrid.DataSource.DataSet.EnableControls; end; end;
source share