Finding the current row in Delphi's TDBGrid

15,898

Solution 1

You can do it like this:

1 - Define a local class that is a copy of TDBGrid (this will let you access private methods):

type
  THackDBGrid = class(TDBGrid);

2 - Then you can cast to your locally defined class, and pull from private methods as in:

function TfrmMain.GetFieldValue(colnum : integer): string;
begin
  Result := THackDBGrid(grdMain).GetFieldValue(colnum);
end;

Or, to get the row #:

function CurrentRowNumber: integer;
  Result := THackDBGrid(grdMain).Row;
end;

This technique is useful in other situations, too, but I cannot claim credit. I got it from here.

Solution 2

I'm not sure if I understand your question, but I'll attempt an answer and maybe you can clarify if this isn't what you are asking.

Since a TDBGrid is tied to a DataSource, the current row is the same as the current row in the data source. You can query the DataSource, either by looking at a primary key value or the RecNo property to determine which record is the current one.

Share:
15,898
BubbaT
Author by

BubbaT

Updated on June 15, 2022

Comments

  • BubbaT
    BubbaT almost 2 years

    Is there a way of finding out which row is current in a TDBGrid?

  • Carlos B. Feitoza Filho
    Carlos B. Feitoza Filho about 11 years
    You started to say the correct thing, but the link you indicated only shows how to get the recordcount but the most important (RecNo or Row or CurrentRow, etc.) cannot be obtained directly from the grid. Sorry
  • mghie
    mghie about 11 years
    @Carlos: What's stopping you from writing Row := TDummyGrid(MyDBGrid).Row instead of RowCount := TDummyGrid(MyDBGrid).RowCount? A tiny bit of thinking is required, you know...
  • Carlos B. Feitoza Filho
    Carlos B. Feitoza Filho about 11 years
    Well... I want to show alternate colors on my Grid, but, the ROW property is not "persistent" between the cursor changes, ie, if you move the cursor top or down on the grid, changing the selection, the ROW property changes for ALL visible rows at same time. I need a way to identify each line individually, independently the current selected row. Now I'm using the RecNo of the linked dataset, but on unidirectional datasets, this property is useless. As you can see, A TINY BIT OF THINKING IS REQUIRED, but YOU was the lazy. Sorry...
  • mghie
    mghie about 11 years
    @Carlos: You're showing a lack of understanding of the grid behaviour, is all. Alternate colours can simply be implemented by using the event parameters of the grid, which include the row and column of the cell to be painted. This has nothing to do with the current row or column. Down-voting an answer because it doesn't fit your own problem (which is different from the original question) is just grand.
  • Joseph Poirier
    Joseph Poirier about 4 years
    This is a great way to work around the rule of having everything in one file to access private items from ancestor classes.