简体   繁体   English

如何通过使用OnCellClick事件在Delphi中获取DBGrid上单元格的内容

[英]How to get the content of a cell on a DBGrid in Delphi by using the OnCellClick event

How can I, by clicking on a cell in the dbgrid on the form, get the selected cell's content? 如何通过单击表单上dbgrid中的单元格来获取所选单元格的内容?

Please note that Delphi's DBGrid is a data-aware grid and is slightly unusual compared with other grids (eg Delphi's TStringGrid) in that the cells of the grid are not readily accessible using Row and Column values. 请注意,Delphi的DBGrid是一个可识别数据的网格,与其他网格(例如Delphi的TStringGrid)相比,它有点不寻常,因为使用Row和Column值不容易访问网格的单元格。

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. 它之所以有效,是因为TDBGrid的编码方式,关联的数据集已同步到当前选定/单击的网格行。 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. 尝试通过操作单元格的文本来避免更改当前记录的值,因为DBGrid会在每一步上与您抗争。

Fwiw, I've seen more "round the houses" ways of getting the cell text, but I prefer this on the KISS principle. Fwiw,我已经看到了更多的“四处走动”的方式来获取单元格文本,但是我更喜欢KISS原则。

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: 请注意,一种更可靠的获取单元格文本的方法如下:其中包括Remy Lebeau建议使用Column.Field而不是SelectedField的建议:

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM