Q:数据查询后 我选中一行数据,在用鼠标滚轮往下翻的时候,选中的行数据就不是我刚才选中的了.同样点击表格那个向下的箭头,也是如此.如何锁定选中的行数据,即时翻页的时候它也不动
地址:http://community.csdn.net/Expert/topic/4084/4084438.xml?temp=.5828516
A:
继承一个TDbgrid,自己画焦点。
WindowProc 中拦截鼠标中键消息,发送WM_VSCROLL消息,控制滚动条随鼠标中键移动
MouseDown中记录选中的行,用dataset的recno属性标记。翻页或鼠标中键以及滚动条的变化不再改变当前行
DrawColumnCell中重画表格
示例:
新建一个form,添加一个TTable,TDatasource,TDbgrid.
============================================
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.