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



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

请注意,Delphi的DBGrid是一个数据感知的网格,与其他网格(例如Delphi的TstringGrid(相比,略有不同寻常使用行和列值不容易访问网格。

最简单的方法就是

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

它起作用是因为TDBGrid的编码方式,关联的数据集为同步到当前选择/单击的网格行。一般来说,从数据集的当前记录中获取值是最简单的,但是您问,所以。尽量避免通过操纵单元格更改当前记录的值发短信,因为DBGRID会与您的每一英寸抗争。

fwiw,我已经看到了更多"围绕房屋"获取单元文本的方法,但是我更喜欢这基于吻原则。

请注意,获取单元文本的一种更强大的方式,其中包括雷米·勒博(Remy Lebeau如下:

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;

最新更新