Search code examples
delphivcldbgrid

DBGrid scroll page instead of row


Well I have an issue with DBGrid vertical scrolling. When I scroll it vertically with mousewheel or vertical scrollbar it moves selected row up and down. I want to make it scroll not selected row but entire grid. Just like it works in Microsoft Excel for example (just to let you know what I mean). Any suggestions?


Solution

  • Well, almost what I'd like to see. Found the post of hanuleye on swissdelhicenter.ch. This code let's you freely scroll DBGrid with mouse wheel.

    unit Unit1;
    
    interface
    
    uses
      Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
      Dialogs, Grids, DBGrids, DB, DBTables;
    
    type
      TForm1 = class(TForm)
        DataSource1: TDataSource;
        Table1: TTable;
        DBGrid1: TDBGrid;
        procedure FormCreate(Sender: TObject);
        procedure DBGridMouseWheel(Sender: TObject; Shift: TShiftState;
          WheelDelta: Integer; MousePos: TPoint; var Handled: Boolean);
      private
        { Private declarations }
      public
        { Public declarations }
      end;
    
      TWheelDBGrid = class(TDBGrid)
      public
        property OnMouseWheel;
      end;
    
    var
      Form1: TForm1;
    
    implementation
    
    {$R *.dfm}
    
    procedure TForm1.FormCreate(Sender: TObject);
    begin
      TWheelDBGrid(DBGrid1).OnMouseWheel := DBGridMouseWheel;
    end;
    
    function GetNumScrollLines: Integer;
    begin
      SystemParametersInfo(SPI_GETWHEELSCROLLLINES, 0, @Result, 0);
    end;
    
    procedure TForm1.DBGridMouseWheel(Sender: TObject; Shift: TShiftState;
      WheelDelta: Integer; MousePos: TPoint; var Handled: Boolean);
    var
      Direction: Shortint;
    begin
      Direction := 1;
      if WheelDelta = 0 then
        Exit
      else if WheelDelta > 0 then
        Direction := -1;
    
      with TDBGrid(Sender) do
      begin
        if Assigned(DataSource) and Assigned(DataSource.DataSet) then
          DataSource.DataSet.MoveBy(Direction * GetNumScrollLines);
        Invalidate;
      end;
    end;
    
    end.