2005. március 22., kedd

How to display the record number in the indicator rectangle of a TDBGrid


Problem/Question/Abstract:

How to display the record number in the indicator rectangle of a TDBGrid

Answer:

Solve 1:

You can show a record number (in case the dataset supports one) in the indicator's rectangle (check if your grid has a dgIndicator in its Options):

{ ... }
TMyDBGrid = class(TDBGrid)
protected
  procedure DrawCell(ACol: Integer; ARow: Integer; ARect: TRect;
    AState: TGridDrawState); override;
  procedure SetColumnAttributes; override;
end;

{ ... }

procedure TMyDBGrid.DrawCell(ACol: Integer; ARow: Integer; ARect: TRect;
  AState: TGridDrawState);
var
  XInt: integer;
begin
  inherited DrawCell(ACol, ARow, ARect, AState);
  if (ACol = 0) and (dgIndicator in Options) and Assigned(DataLink.DataSet)
    and (DataLink.DataSet.Active) then
  begin
    if dgTitles in Options then
      if ARow = 0 then
        exit
      else
        dec(ARow);
    Canvas.FillRect(ARect);
    DataLink.ActiveRecord := ARow;
    XInt := DataLink.DataSet.RecNo;
    Canvas.TextOut(ARect.Left, ARect.Top, intToStr(XInt));
  end;
end;

procedure TMyDBGrid.SetColumnAttributes;
begin
  inherited SetColumnAttributes;
  if (dgIndicator in Options) then
    ColWidths[0] := 20;
end;

This code worked fine for Paradox tables with BDE datasets and for Interbase tables with InterBase Express's TIBTable.


Solve 2:

Drop a TDBGrid on a form. Add all the required columns through the columns editor. Set the fieldname and title caption. Add an extra column and set it right at the top of the columns list, so that this will appear as the first column to display the record number. Don't set a field name for this column. Set any title caption like 'Row No'. Also make sure that the extra added column for displaying the row number is read-only.

procedure TForm1.DBGrid1DrawColumnCell(Sender: TObject; const Rect: TRect;
  DataCol: Integer; Column: TColumn; State: TGridDrawState);
begin
  if DataCol = 0 then
  begin
    if table1.State = dsInsert then
    begin
      if Table1.RecNo < 0 then
        DBGrid1.Canvas.TextOut(rect.Left + 2, rect.Top + 3,
                                 IntTostr(Table1.recordcount + 2))
      else
        DBGrid1.Canvas.TextOut(rect.Left + 2, rect.Top + 3, IntTostr(Table1.RecNo));
    end
    else
      DBGrid1.Canvas.TextOut(rect.Left + 2, rect.Top + 3, IntTostr(Table1.RecNo));
  end;
end;

procedure TForm1.DBGrid1ColEnter(Sender: TObject);
begin
  if DBGrid1.SelectedIndex = 0 then
    DBGrid1.SelectedIndex := 1;
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
  DBGrid1.SelectedIndex := 1;
end;

Nincsenek megjegyzések:

Megjegyzés küldése