Search code examples
delphidelphi-11-alexandria

How to get the clicked column on TDBGrid.DblClick(Sender: TObject)?


When using the OnDblClick event of a TDBGrid, how can i know what column was double clicked ?

This is easy with the OnCellClick as it has a TColumn parameter, but not on OnDblClick.


Solution

  • The OnDblClick event doesn't give you any information about the click, in particular where the click was performed, let alone which grid cell was clicked on. So, you will have to determine that information manually.

    Try this:

    • Get the current mouse position within the grid, by passing Mouse.CursorPos to TDBGrid.ScreenToClient()
    • Then, use TDBGrid.MouseCoord() to determine the row/column indexes of the cell that is underneath the mouse.
    • Then, check if the cell row/column corresponds to a data cell, and if so then use the TDBGrid.SelectedIndex property to index into the TDBGrid.Columns property.

    This is basically the same thing that TDBGrid does internally when firing the OnCellClick event, only it does this in response to a MouseUp event, which provides the mouse coordinates within the grid, thus skipping the 1st step above.

    For example:

    type
      TDBGridAccess = class(TDBGrid)
      end;
    
    procedure TMyForm1.DBGrid1DblClick(Sender: TObject);
    var
      TitleOffset: Byte;
      Pt: TPoint;
      Cell: TGridCoord;
      Column: TColumn;
    begin
      TitleOffset := Ord(dgTitles in DBGrid1.Options);
      Pt := DBGrid1.ScreenToClient(Mouse.CursorPos);
      Cell := DBGrid1.MouseCoord(Pt.X, Pt.Y);
      if (Cell.X >= TDBGridAccess(DBGrid1).IndicatorOffset) and (Cell.Y >= TitleOffset) then
      begin
        Column := DBGrid1.Columns[DBGrid1.SelectedIndex];
        // use Column as needed...
      end;
    end;
    

    UPDATE: based on @UweRaabe's comments, you should be able to just use TDBGrid.SelectedIndex by itself:

    procedure TMyForm1.DBGrid1DblClick(Sender: TObject);
    var
      Index: Integer;
      Column: TColumn;
    begin
      Index := DBGrid1.SelectedIndex;
      if (Index <> -1) then
      begin
        Column := DBGrid1.Columns[Index];
        // use Column as needed...
      end;
    end;