从TCustomDBGrid继承一个类:
TMyDBGrid = class(TCustomDBGrid)
protected
procedure DrawCell(ACol, ARow: Longint; ARect: TRect; AState: TGridDrawState); override;
procedure WMVScroll(var Message: TWMVScroll); message WM_VSCROLL;
public
ColNo: Integer;//显示序号的列号
RecNo: Integer;//第一可见行行号
end;
然后,比如点击某Button进行查询:
procedure TForm1.Button1Click(Sender: TObject);
var
I: Integer;
Column: TColumn;
begin
for I := MyDBGrid.Columns.Count - 1 downto 0 do MyDBGrid.Columns.Free;
Query1.Open;
Column := TColumn.Create(MyDBGrid.Columns);
Column.Title.Caption := '序号';
MyDBGrid.ColNo := 1;
MyDBGrid.RecNo := 0;
for I := 0 to Query1.FieldCount - 1 do begin
Column := TColumn.Create(MyDBGrid.Columns);
Column.Field := Query1.Fields;
end;
end;
在DrawCell里显示序号:
procedure TMyDBGrid.DrawCell(ACol, ARow: Longint; ARect: TRect; AState: TGridDrawState);
var
s: String;
R: TRect;
begin
inherited;
if DataSource.DataSet.Active and (ACol = ColNo) and (ARow > 0) then begin
s := IntToStr(RecNo + ARow);
R := ARect;
InflateRect(R, -2, -2);
DrawText(Canvas.Handle, PChar(s), Length(s), R, DT_RIGHT)
end;
end;
难点在于控制第一可见行的行号:
procedure TMyDBGrid.WMVScroll(var Message: TWMVScroll);
begin
inherited;
with Message do
case ScrollCode of
SB_LINEUP: Dec(RecNo);
SB_LINEDOWN: Inc(RecNo);
SB_PAGEUP: Dec(RecNo, VisibleRowCount);
SB_PAGEDOWN: Inc(RecNo, VisibleRowCount);
SB_THUMBPOSITION:
case Pos of
0: RecNo := 0;
1: Dec(RecNo, VisibleRowCount);
2: Exit;
3: Inc(RecNo, VisibleRowCount);
4: RecNo := DataSource.DataSet.RecordCount;
end;
SB_BOTTOM: RecNo := DataSource.DataSet.RecordCount;
SB_TOP: RecNo := 0;
end;
if RecNo < 0 then RecNo := 0;
if RecNo > DataSource.DataSet.RecordCount - VisibleRowCount then
RecNo := DataSource.DataSet.RecordCount - VisibleRowCount;
Refresh;
end;
对以上程序进行了简单测试,效果还行(我用的是SQL SERVER的查询)。
但是最后一段对RecNo的控制还不是很有把握,主要是因为RecordCount
不一定可靠,实在不行你可以先用一个SELECT Count(*)查询把记录数
取出来记在一个变量里。
——再不行你可以看看TCustomDBGrid的源码。