procedure TForm1.Table1CalcFields(DataSet:   TDataSet);
begin
table1.FieldValues['no']:=table1.RecNo;
end;
//聲明全局變量i
procedure TForm1.DBGrid1DrawColumnCell(Sender: TObject; const Rect: TRect;
DataCol: Integer; Column: TColumn; State: TGridDrawState);
begin
with DBGrid1.DataSource.DataSet do
begin
if DataCol = then //設置在第一列
begin
if state<>dsInsert then i:= recno; //這句是關鍵。。。
DBGrid1.Canvas.TextRect(Rect, Rect.Left + , Rect.Top + , IntToStr(i));
inc(i); //將i加1
end;
end;
end; procedure TForm1.DataSource1StateChange(Sender: TObject);
begin //狀態改變時將i置為1
i:=;
end; 問題完美解決了,代碼也很簡單,只是加了一個中間變量 i 。
到目前為為止,網上還未見到此種解決方案,如有雷同,純屬巧合。 以上方法後來證明還是有點問題,修正如下:
var
Form1: TForm1;
i:integer;
bflag,bflag2:boolean; implementation {$R *.dfm} procedure TForm1.Button1Click(Sender: TObject);
begin
adoquery1.Open;
end; procedure TForm1.DBGrid1DrawColumnCell(Sender: TObject; const Rect: TRect;
DataCol: Integer; Column: TColumn; State: TGridDrawState);
var
rect1:TRect;
sValue :string;
ss:boolean;
begin
if DataCol = then //設置在第一列
begin
if DBGrid1.DataSource.DataSet.state<>dsInsert then
i:= DBGrid1.DataSource.DataSet.recno; Rect1 := Rect;
with dbgrid1 do
begin
Canvas.Brush.Color := clBtnFace;
sValue := IntToStr(i);
Canvas.FillRect(Rect1);
Canvas.Pen.Width := ;
Canvas.Pen.Color := clWhite;
Canvas.MoveTo(Rect1.Left, Rect1.Bottom);
Canvas.LineTo(Rect1.Left, Rect1.Top);
Canvas.LineTo(Rect1.right, Rect1.Top);
Canvas.Pen.Color := clBtnShadow;
Canvas.LineTo(Rect1.right, Rect1.Bottom - );
Canvas.LineTo(Rect1.Left, Rect1.Bottom - );
Rect1.Top := Rect1.Top +;
if State = [gdSelected, gdFocused] then
begin
if bflag=true then
begin
sValue:=inttostr(datasource.DataSet.RecordCount +);
i:=datasource.DataSet.RecordCount +;
ss:=true;
end;
Canvas.Font.Color := clred;
end
else
begin
Canvas.Font.Color := clgreen;
end;
DrawText(Canvas.Handle, PChar(sValue), Length(sValue), Rect1, DT_CENTER);
end;
if i<=dbgrid1.DataSource.DataSet.RecordCount then
begin
inc(i);
end
else
begin
if (ss<>true) then
i:=dbgrid1.DataSource.DataSet.RecordCount+ -TDrawGrid(DBgrid1).RowCount ;
end;
end
else bflag2:=false;
end; procedure TForm1.DataSource1StateChange(Sender: TObject);
begin
if dbgrid1.DataSource.DataSet.State <>dsbrowse then
begin
i:=dbgrid1.DataSource.DataSet.RecordCount+ -TDrawGrid(DBgrid1).RowCount ;
bflag := true;
end
else
bflag:=false;
end; procedure TForm1.DBGrid1ColEnter(Sender: TObject);
begin
if (bflag=true)and (dbgrid1.SelectedField.FieldNo <>) then
begin
i:=dbgrid1.DataSource.DataSet.RecordCount+ -TDrawGrid(DBgrid1).RowCount;
dbgrid1.Refresh;
end;
end; procedure TForm1.DBGrid1ColExit(Sender: TObject);
begin
if (bflag=true)and (dbgrid1.SelectedField.FieldNo =) then
begin
i:=dbgrid1.DataSource.DataSet.RecordCount+;
dbgrid1.Refresh;
end;
end; end.
05-08 15:08