我想要调整一个TDBGrid高度给定一个VisibleRows参数。网格可能有或可能没有标题。
假设我从db中选择了100条记录,但我希望网格高度能够调整以显示前10行(使其可见)。数据集仍将保存100条记录。
即
procedure SetVisibleRows(DBGrid: TCustomDBGrid; VisibleRows: Integer);
begin
...
DBGrid.Height := ???
end;我知道如何获得可见的行:
type
TCustomGridHack = class(TCustomGrid);
function GetVisibleRows(DBGrid: TCustomDBGrid): Integer;
begin
Result := TCustomGridHack(DBGrid).VisibleRowCount;
end;但是,有没有一种方法来设置VisibleRowCount
发布于 2017-11-15 10:55:04
这似乎很有效(也许可以进行更多的优化):
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;或者使用@nil建议的TGridDrawInfo。它产生了更精确的结果(我稍微修改了一下):
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;正如@nil所提到的,RowHeight也可以用以下方法计算:
RowHeight := DrawInfo.Vert.GetExtent(DrawInfo.Vert.FirstGridCell) + DrawInfo.Vert.EffectiveLineWidth; 不过,我没注意到有什么不同。(应进一步调查)。
可以进一步改进上面的内容,使TDBGrid滚动条调整得更好:
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;https://stackoverflow.com/questions/47303291
复制相似问题