Configure TDBGrid Visible Rows

I want to adjust TDBGrid height with VisibleRows parameter. the grid may or may not have headers.

Suppose I select 100 records from db, but I want the grid height to be adjusted to show the first 10 rows (make them visible). the dataset will still contain 100 records.

i.e.

 procedure SetVisibleRows(DBGrid: TCustomDBGrid; VisibleRows: Integer); begin ... DBGrid.Height := ??? end; 

I know how to get visible lines:

 type TCustomGridHack = class(TCustomGrid); function GetVisibleRows(DBGrid: TCustomDBGrid): Integer; begin Result := TCustomGridHack(DBGrid).VisibleRowCount; end; 

But is there a way to set VisibleRowCount ?

+5
source share
1 answer

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; 
+2
source

Source: https://habr.com/ru/post/1273391/


All Articles