首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >设置TDBGrid可见行

设置TDBGrid可见行
EN

Stack Overflow用户
提问于 2017-11-15 09:08:55
回答 1查看 1.9K关注 0票数 5

我想要调整一个TDBGrid高度给定一个VisibleRows参数。网格可能有或可能没有标题。

假设我从db中选择了100条记录,但我希望网格高度能够调整以显示前10行(使其可见)。数据集仍将保存100条记录。

代码语言:javascript
复制
procedure SetVisibleRows(DBGrid: TCustomDBGrid; VisibleRows: Integer);
begin
  ...
  DBGrid.Height := ???
end;

我知道如何获得可见的行:

代码语言:javascript
复制
type
  TCustomGridHack = class(TCustomGrid);

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

但是,有没有一种方法来设置VisibleRowCount

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-11-15 10:55:04

这似乎很有效(也许可以进行更多的优化):

代码语言:javascript
复制
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。它产生了更精确的结果(我稍微修改了一下):

代码语言:javascript
复制
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也可以用以下方法计算:

代码语言:javascript
复制
RowHeight := DrawInfo.Vert.GetExtent(DrawInfo.Vert.FirstGridCell) + DrawInfo.Vert.EffectiveLineWidth; 

不过,我没注意到有什么不同。(应进一步调查)。

可以进一步改进上面的内容,使TDBGrid滚动条调整得更好:

代码语言:javascript
复制
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
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47303291

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档