Hi,
I have an application with a TDBGrid and I want to implement a functionality that allows to copy the content of a cell:
1. The user right clicks on a cell.
2. A TPopMenu appears with several options, including “Copy cell”.
3. When selecting “Copy cell”, the content is copied to the clipboard.
The desired behavior is very simple, but I am having problems with the implementation, especially getting the correct cell value.
procedure TfrmMain.DBGrid1MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
var
Coord: TGridCoord;
CellValue: String;
Tmp: Integer;
begin
if Button = mbRight then
begin
Coord:= DBGrid1.MouseCoord(X, Y);
if (Coord.X >= 0) and (Coord.Y >= 0) then
begin
Tmp:= DBGrid1.DataSource.DataSet.RecNo;
DBGrid1.DataSource.DataSet.RecNo:= Coord.Y;
CellValue:= DBGrid1.Columns[Coord.X].Field.AsString;
DBGrid1.DataSource.DataSet.RecNo:= Tmp;
ShowMessage(CellValue);
end;
end;
end;
With this approach I get the correct value of any cell, but I have the following problems:
1. If the user previously left-clicks anywhere in the lower second half of the TDBGrid, and then right-clicks on the cell he wants to copy, the TDBGrid scrolls and returns an incorrect cell value.
2. If the cell you want to copy is further down in the TDBGrid and you therefore need to scroll down, the cell value returned is incorrect.
I understand that (at least part of) the problem lies in the RecNo:= Coord.Y assignment, since Coord.Y returns the location of the cursor on the Y axis, and this only matches the first RecNo values when the TDBGrid is on the first screen. However, I confess that I can't think of any other way to get the desired cell location.
Could someone please help me with this?