How to catch scrolling event in DBGrid in Delphi

Tofig Hasanov picture Tofig Hasanov · Nov 12, 2009 · Viewed 10.6k times · Source

I have a DBGrid, I need to run some code, each time the horizontal scrollbar is used. I couldn't find such event in DBGrid. Can you advise something?

Answer

Francesca picture Francesca · Nov 12, 2009

There is a WMHScroll procedure in TCustomGrid, but it is private. You can't use it in a DBGrid.
You would have to create your own TDBGrid descendant and do your own

procedure WMHScroll(var Msg: TWMHScroll); message WM_HSCROLL;

or do some seriously bad hacking...

Update: trick/hack to sneak your code in...

[...]
    uses
      Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
      Dialogs, DB, ADODB, Grids, DBGrids;

    type
      // Hack to redeclare your TDBGrid here whitout the the form designer going mad
      TDBGrid = class(DBGrids.TDBGrid)
        procedure WMHScroll(var Msg: TWMHScroll); message WM_HSCROLL;
      end;

      TForm8 = class(TForm)
        DBGrid1: TDBGrid;
        DataSource1: TDataSource;
        ADODataSet1: TADODataSet;
        ADOConnection1: TADOConnection;
      private
        { Private declarations }
      public
        { Public declarations }
      end;

    var
      Form8: TForm8;

    implementation

    {$R *.dfm}

    { TDBGrid }

    procedure TDBGrid.WMHScroll(var Msg: TWMHScroll);
    begin
      case Msg.ScrollCode of
        SB_ENDSCROLL: OutputDebugString('SB_ENDSCROLL') ;
        SB_LEFT:OutputDebugString('SB_LEFT');
        SB_RIGHT:OutputDebugString('SB_RIGHT');
        SB_LINELEFT:OutputDebugString('SB_LINELEFT');
        SB_LINERIGHT:OutputDebugString('SB_LINERIGHT');
        SB_PAGELEFT:OutputDebugString('SB_PAGELEFT');
        SB_PAGERIGHT:OutputDebugString('SB_PAGERIGHT');
        SB_THUMBPOSITION:OutputDebugString('SB_THUMBPOSITION');
      end;
      inherited; // to keep the expected behavior
    end;
[...]

Update2: Note that you can move your special TDBGrid code to a separate unit (recommended), just be sure to put this unit name AFTER DBGrids in your Form's uses clause.