views:

152

answers:

1

I have OnMouseMove event, during which I want to find a value of certain cell (not neccesarily the one under the mouse). Basically the question is: How to access cell data using its x and y coordinates without selecting it, changing focus etc?

+1  A: 

Tofig, you can use the MouseCoord procedure to get the current row and col, but to show the value of the pos [Col,Row] you must set the DataLink.ActiveRecord property to the Row value and create a new class descendent to access the protected property.

check this code

type
 THackGrid = class(TCustomDBGrid); //Create a new class to access the protected properties


procedure TForm1.DBGrid1MouseMove(Sender: TObject; Shift: TShiftState; X,
  Y: Integer);
var
    Cell             : TGridCoord;
    Row,Col          : integer;
    OrigActiveRecord : integer;
begin
    inherited;
    Cell:=DBGrid1.MouseCoord(X,Y);
    Col:= Cell.X;
    Row:= Cell.Y;

  if dgTitles in DBGrid1.Options    then  Dec(Row); //if the titles are shown then adjust Row index (-1);
  if dgIndicator in DBGrid1.Options then  Dec(Col); //if the indicator is shown then adjust the Column index (-1);

    if THackGrid(DBGrid1).DataLink.Active and (Row>=0) and (Col>=0)  then
    begin
       OrigActiveRecord:=THackGrid(DBGrid1).DataLink.ActiveRecord; //save the original index
      try
       THackGrid(DBGrid1).DataLink.ActiveRecord:= Row;
       Label1.Caption:=DBGrid1.Columns[Col].Field.AsString; //show the current value in a tlabel
      finally
        THackGrid(DBGrid1).DataLink.ActiveRecord:= OrigActiveRecord; //restore the index
      end;
    end;
end;
RRUZ
You don't need to get MouseCoord. OnMouseMove event already has them.
Linas
@Linas, the X and Y values return a point (X,Y) , you need the function `MouseCoord` to convert theses values to the col and row indexes, check this link http://docwiki.embarcadero.com/VCL/en/Grids.TCustomGrid.MouseCoord
RRUZ
Thanks, this worked. I have a feeling though, that there should be some easier way. I mean DbGrid should store these values somewhere, in order to paint them. Can't we just directly access them somehow?
Tofig Hasanov