重新整理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!