Detect which cell was clicked in TDBGrid when dgRowSelect is set to True?

srayner picture srayner · Dec 18, 2012 · Viewed 10.4k times · Source

In Delphi 2010 is there any way to detect which cell was clicked when dgRowSelect is set to True ?

Normally I would use the OnCellClick(Column: TColumn) event handler, but this does not work as expected. With dgRowSelect = False this procedure gets passed the column that was clicked, but with dgRowSelect = True this procedure is passed the first column, regardless of which column was clicked.

I can't work out where the code is that calls the OnCellClick passing in the TColumn parameter, if I could find that I might be able to work out how to fix this odd behaviour.

Answer

Ken White picture Ken White · Dec 18, 2012

You can use the mouse coordinates to get the column. After calling TDBGrid.MouseCoord, the returned TGridCoord.X contains the column number, and the Y contains the row (which, of course, you already have):

procedure TForm1.DBGrid1CellClick(Column: TColumn);
var
  Pt: TPoint;
  Coord: TGridCoord;
  ClickCol: Integer;
begin
  Pt := DBGrid1.ScreenToClient(Mouse.CursorPos);
  Coord := DBGrid1.MouseCoord(Pt.X, Pt.Y);
  ClickCol := Coord.X;
  ShowMessage('You clicked column ' + IntToStr(ClickCol));
end;

More info on TGridCoord in the documentation.

Tested using the same app used for my answer to your previous question.