2011. május 18., szerda

How to retrieve cell values of a TDBGrid using MouseCoord


Problem/Question/Abstract:

I want to display a help window containing the value of the data cell under the cursor.

Answer:

The trick is to use the protected DataLink property of TDBGrid which is of typeTGridDataLink. One can see that property as being kind of a buffer for a displayed page in TDBGrid. Take note that I'm using D6 and that I used OnMouseMove. Delphi6's TDBGrid has a OnMouseMove event whereas D4 has not (I don't know about D5). If you are using D4, you can hack the OnMouseMove event which comes from TControl.


type
  THackDbGrid = class(TDBGrid);

procedure TForm1.DBGrid1MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer);
var
  gc: TGridCoord;
  dbg: TDBGrid;
  SavedActiveRec: integer;
begin
  dbg := TDBGrid(Sender);
  gc := dbg.MouseCoord(X, Y);
  if (gc.X > 0) and (gc.X < dbg.Columns.Count) and (gc.Y > 0) then
  begin
    SavedActiveRec := THackDbGrid(Dbg).DataLink.ActiveRecord;
    THackDbGrid(Dbg).DataLink.ActiveRecord := gc.Y - 1;
    Dbg.Hint := dbg.Columns[gc.X - 1].Field.AsString;
    THackDbGrid(Dbg).DataLink.ActiveRecord := SavedActiveRec;
  end
  else
    Dbg.Hint := '';
end;

Nincsenek megjegyzések:

Megjegyzés küldése