How to move the active record in a table to a certain position on a TDBGrid (2) (Views: 101)


Does anyone have a suggestion as to how I can force a DBGrid to always have the "current" record in the top row of the grid? I am navigating the table with the use of a Navigator tool and would like to display the next several records in the table in the grid.


I think I found a usable, if not particularly elegant solution: Use a cracker class to locate one's position within the grid, and use that to jump forward and back through the dataset to position the current record at the top.

My test case works only from the Navigator. Moving in either direction with the Navigator will reposition the current record to the top of the grid, if there are enough records after the current one to allow it.

If you want to set up a test case: Drop a Navigator and Grid on a new project, with all other requisite components (table, query, datasource, etc.), and replace the unit's code with the following. Hook up the Navigator's OnClick to the appropriate routine.

unit Unit1;



  Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
  ExtCtrls, DBCtrls, Db, DBTables, Grids, DBGrids, StdCtrls;

  TForm1 = class(TForm)
    DBGrid1: TDBGrid;
    DataSource1: TDataSource;
    Table1: TTable;
    DBNavigator1: TDBNavigator;
    procedure DBNavigator1Click(Sender: TObject; Button: TNavigateBtn);

  TGridCracker = class(TDBGrid);

  Form1: TForm1;


{$R *.DFM}

procedure TForm1.DBNavigator1Click(Sender: TObject; Button: TNavigateBtn);
  RowsActuallyMoved: Integer;
  with TGridCracker(DBGrid1) do
    BeginUpdate; {seems ineffectual, like other draw-locking mechanisms, but...}
    if Row <> TopRow then
      RowsActuallyMoved := Table1.MoveBy(RowCount);
      Table1.MoveBy(-RowsActuallyMoved); {take care of boundary cases; ie. EOF}


<< Back to main page