加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

delphi – 设置TDBGrid可见行

发布时间:2020-12-15 09:47:54 所属栏目:大数据 来源:网络整理
导读:我想在给定VisibleRows参数的情况下调整TDBGrid高度.网格可能有也可能没有标题. 假设我从数据库中选择了100条记录,但我想调整网格高度以显示前10行(使它们可见).数据集仍将保留100条记录. 即 procedure SetVisibleRows(DBGrid: TCustomDBGrid; VisibleRows:
我想在给定VisibleRows参数的情况下调整TDBGrid高度.网格可能有也可能没有标题.

假设我从数据库中选择了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?

解决方法

这似乎工作(也许可以更优化):

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;

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读