2010. augusztus 9., hétfő

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


Problem/Question/Abstract:

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.

Answer:

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;

{$O-}

interface

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

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

  TGridCracker = class(TDBGrid);

var
  Form1: TForm1;

implementation

{$R *.DFM}

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

end.

Nincsenek megjegyzések:

Megjegyzés küldése