首页 > 解决方案 > 如何使用 OnCellClick 事件在 Delphi 中的 DBGrid 上获取单元格的内容

问题描述

如何通过单击表单上 dbgrid 中的单元格来获取所选单元格的内容?

请注意,Delphi 的 DBGrid 是一个数据感知网格,与其他网格(例如 Delphi 的 TStringGrid)相比,它有点不寻常,因为使用 Row 和 Column 值不容易访问网格的单元格。

标签: databasedelphidbgrid

解决方案


最简单的方法就是

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

它之所以有效,是因为 TDBGrid 的编码方式,关联的数据集同步到当前选择/单击的网格行。一般来说,从数据集的当前记录中获取值是最容易的,但是你问了,所以。尽量避免通过操作单元格的文本来更改当前记录的值,因为 DBGrid 会在每一寸地方都与您抗争。

Fwiw,我已经看到了更多“绕​​房子”获取单元格文本的方法,但我更喜欢 KISS 原则。

请注意,获取单元格文本的一种更可靠的方法如下:

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;

推荐阅读