DataGrid滚动时当前记录不变

unit Unit1;

interface
{鼠标中键/滚动条/翻页操作时锁定Dbgrid的选定纪录不动
  by jinjazz}
uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, Grids, DBGrids, DB, DBTables, StdCtrls;

 

type
  TDBGrid = class(DBGrids.TDBGrid)
  private
    FOldGridWnd: TWndMethod;
    SelectedRow: integer;
    procedure NewGridWnd(var Message: TMessage);
  protected
    procedure DrawColumnCell(const Rect: TRect; DataCol: Integer;
      Column: TColumn; State: TGridDrawState); override;
    procedure MouseDown(Button: TMouseButton; Shift: TShiftState;
      X, Y: Integer); override;
  public
    constructor Create(AOwner: TComponent); override;
  end;
type
  TForm1 = class(TForm)
    Table1: TTable;
    DataSource1: TDataSource;
    DBGrid1: TDBGrid;
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

{ TDBGrid }

constructor TDBGrid.Create(AOwner: TComponent);
begin
  inherited;
  Options := Options + [dgindicator];
  Self.FOldGridWnd := Self.WindowProc;
  Self.WindowProc := NewGridWnd;
  SelectedRow := -1;
end;

procedure TDBGrid.NewGridWnd(var Message: TMessage);
var
  IsNeg: Boolean;
begin

  if Message.Msg = WM_MOUSEWHEEL then
  begin
    IsNeg := Short(Message.WParamHi) < 0;
    if IsNeg then
      SendMessage(Handle, WM_VSCROLL, SB_LINEDOWN, 0)
    else
      SendMessage(Handle, WM_VSCROLL, SB_LINEUP, 0)
  end
  else
    Self.FOldGridWnd(Message);

end;

procedure TDbGrid.DrawColumnCell(const Rect: TRect; DataCol: Integer;
  Column: TColumn; State: TGridDrawState);
begin
if SelectedRow=-1 then  SelectedRow:=DataSource.DataSet.RecNo;
  Color := clinfobk;
  Options := Options + [dgRowSelect];
  if ((State = [gdSelected]) or (State = [gdSelected, gdFocused])) then
  begin
    Canvas.Brush.color := Color;
    Canvas.Font.Color := Font.Color;
  end;
  if DataSource.DataSet.RecNo = selectedRow then
    Canvas.Brush.color := clRed; //当前行以红色显示,其它行使用背景的浅绿色
  Canvas.pen.mode := pmmask;
  DefaultDrawColumnCell(Rect, DataCol, Column, State);
end;

procedure TDBGrid.MouseDown(Button: TMouseButton; Shift: TShiftState; X,
  Y: Integer);
var
  Cell: TGridCoord;
begin
  inherited;
  if Button = mbLeft then
  begin
    selectedRow := DataSource.DataSet.RecNo;
    repaint;
  end;
end;

end.
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值