6

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.

TLama
  • 75,147
  • 17
  • 214
  • 392
srayner
  • 1,799
  • 4
  • 23
  • 39

1 Answers1

15

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.

Community
  • 1
  • 1
Ken White
  • 123,280
  • 14
  • 225
  • 444
  • Perfect answer. Gives me exactly what i need. If it helps anyone else i used this to give me the name of the database field; DBGrid1.Columns[ClickCol - 1].Field.FieldName – srayner Dec 19 '12 at 09:38
  • +1 This answer helped me too, but is it me or there is something wrong with the naming of the properties? Normally mouse coordinates are understood as screen relative position. – Laureano Bonilla Oct 27 '15 at 17:24
  • The ScreenToClient might do the conversion, am I right? – Laureano Bonilla Oct 27 '15 at 17:26
  • @LaureanoBonilla: The `ScreenToClient` converts to grid-specific coordinates, which are passed to `MouseCoord` to convert to row/column location. – Ken White Oct 27 '15 at 18:01