Reputation: 133
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.
Upvotes: 1
Views: 7068
Reputation: 30715
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;
Upvotes: 2