1
votes

How can I, by clicking on a cell in the dbgrid on the form, get the selected cell's content?

Please note that Delphi's DBGrid is a data-aware grid and is slightly unusual compared with other grids (e.g. Delphi's TStringGrid) in that the cells of the grid are not readily accessible using Row and Column values.

1
Clearly anyone who could answer this question would already know what TDBGrid is and how it works. You've spent more time on an unnecessary note than you have in actually writing a question.Ken White
@KenWhite: Actually it was me who added the 2nd para, at the request of a moderator who evidently wasn't familiar with TDBGrid and apparently wasn't aware of the specific problem the OP is asking about.MartynA

1 Answers

2
votes

The easiest way to do this is simply

procedure TForm1.DBGrid1CellClick(Column: TColumn);
var
  S : String;
begin
  S := DBGrid1.SelectedField.AsString;
  Caption := S;
end;

It works because the way TDBGrid is coded, the associated dataset is synchronized to the currently selected/clicked grid row. Generally speaking, it's easiest to get values from the current record of the dataset, but you asked, so. Try to avoid changing the current record's values by manipulating the cell's text because the DBGrid will fight you every inch of the way.

Fwiw, I've seen more "round the houses" ways of getting the cell text, but I prefer this on the KISS principle.

Note that a more robust way of getting the cell text, which includes Remy Lebeau's suggestion to use Column.Field instead of SelectedField, is as follows:

procedure TForm1.DBGrid1CellClick(Column: TColumn);
var
  S : String;
  AField : TField;
begin
  AField := DBGrid1.SelectedField;
  //  OR AField := Column.Field;


  //  Note:  If the DBGrid happens to have an unbound column (one with
  //         no TField assigned to it) the AField obtained mat be Nil if
  //         it is the unbound column which is clicked.  So we should check for
  //         AField being Nil

  if AField <> Nil then begin
    S := AField.AsString;
    Caption := S;
  end;
end;