刷新dbgrid 而不失去当前行位置

http://www.delphishare.com/?/1207-1-0-1-1.html

http://delphi.about.com/od/delphitips2008/qt/dbgrid_row_pos.htm

google翻译并整理

我们有一个Delphi的数据库应用程序,上面有个DBGrid和一个数据集:
 

DBGrid是用来显示来自数据集(查询或表)的数据,根据设计,当您调用已经打开的数据集的Refresh方

法(例如使用DBNavigator的Refresh),当前行的位置将被设置为0 (第一个记录)。

这意味着,如果用户选择了DBGrid的底部某个地方的一行记录,在刷新后,当前激活的行将改为第一行:

(


如果你一直在问:“有什么办法重新查询或刷新后,让TDBGrid中的数据留在准确位置(不改变位置)?

”这里的一个答案的问题:

刷新DBGrid的数据 - 保留行的位置
这里的一个小程序控制刷新DBGrid的内容后不会失去该行的位置。


 //THackDBGrid = class(TDBGrid)
 
 //refresh datagrid data - preserve rowposition
 procedure Refresh_PreservePosition;
 var
   rowDelta: Integer;
   row: integer;
   recNo: integer;
   ds : TDataSet;
 begin
   ds :=THackDBGrid(DBGrid1).DataSource.DataSet;
 
   rowDelta := -1 +THackDBGrid(DBGrid1).Row;
   row := ds.RecNo;
 
   ds.Refresh;
 
   with ds do
   begin
    DisableControls;
    RecNo := row;
    MoveBy(-rowDelta) ;
    MoveBy(rowDelta) ;
    EnableControls;
   end;
 end;


 请注意这里使用的保护破解(THackDBGrid)来获得隐藏的(protected)Row属性!

英文原文

There's DBGrid, there's adataset and we have a data awareDelphi application :)

When DBGrid is used to display data from a dataset (query ortable), by design, after you call Refresh method on a dataset(re-open) (for example, using a DBNavigator), the current row position will be setto zero (first record).

This means that if a user has selected a row somewhere near thebottom of a DBGrid, after a Refresh, the active row will be changedto first row :(

If you have been asking "Is there any way to reopen or refresh aquery, leaving the TDBGrid data exactly where it is (withoutchanging the positions)?" Here's one answer to the problem:

Refresh DBGrid Data - Preserve Row Position

Here's a handly little procedure to refresh the content of aDBGrid without losing the row position.

复制代码
 //THackDBGrid = class(TDBGrid)
 
 //refresh datagrid data - preserve row position
 procedure Refresh_PreservePosition;
 var
   rowDelta: Integer;
   row: integer;
   recNo: integer;
   ds : TDataSet;
 begin
   ds := THackDBGrid(DBGrid1).DataSource.DataSet;
 
   rowDelta := -1 + THackDBGrid(DBGrid1).Row;
   row := ds.RecNo;
 
   ds.Refresh;
 
   with ds do
   begin
     DisableControls;
     RecNo := row;
     MoveBy(-rowDelta) ;
     MoveBy(rowDelta) ;
     EnableControls;
   end;
 end;
 
复制代码

Note the protected hack used here(THackDBGrid) to get the hidden (protected) Row property!

posted on   癫狂编程  阅读(134)  评论(0编辑  收藏  举报

编辑推荐:
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
阅读排行:
· 全网最简单!3分钟用满血DeepSeek R1开发一款AI智能客服,零代码轻松接入微信、公众号、小程
· .NET 10 首个预览版发布,跨平台开发与性能全面提升
· 《HelloGitHub》第 107 期
· 全程使用 AI 从 0 到 1 写了个小工具
· 从文本到图像:SSE 如何助力 AI 内容实时呈现?(Typescript篇)

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
好的代码像粥一样,都是用时间熬出来的
点击右上角即可分享
微信分享提示