How to get the middle row number in the current DBGrid View

1k views Asked by At

Can anyone help me get the middle row number of the current DBGrid view?

I was able to get the following but could not get the row number of it. I also do not know what is this for.

DBGRid1.CenterCurRowInView

Update: By the way, the grid is in scrolled view state.

Adding Screenshot:

enter image description here

2

There are 2 answers

3
MartynA On BEST ANSWER

My answer here shows how to determine the current row number and number of rows in a DBGrid:

type
  TMyDBGrid = Class(TDBGrid);

function TForm1.GetGridRow: Integer;
begin
  Result := TmyDBGrid(DBGrid1).Row;
end;

function TForm1.GridRowCount : Integer;
begin
  Result := TmyDBGrid(DBGrid1).RowCount;
end;

This avoids the need for a class helper and will work in Delphi versions which pre-date support for them.

Btw, the grid only has a unique "middle row" if the number of rows being displayed in the grid is odd, of course. Also be careful of what you actually need, because the "middle row" is ambiguous if the number of rows in the dataset is less than the number of rows the grid can simultaneously display.

12
fpiette On

The row count of the grid is given by the formula:

RowCount := DBGrid1.ClientHeight div (RowHeight + 1);

The middle row is obviously half that value (Also depends if you count the title row or not).

RowHeight is not published in DBGrid. To get hand on it, you can use an interposer class:

type
    TInterDBGrid = class(TDBGrid);

And use it like this:

RowHeight := TInterDBGrid(DBGrid1).RowHeights[0];

The interposer class must be defined before the form.