簡體   English   中英

如何通過使用OnCellClick事件在Delphi中獲取DBGrid上單元格的內容

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

如何通過單擊表單上dbgrid中的單元格來獲取所選單元格的內容?

請注意,Delphi的DBGrid是一個可識別數據的網格,與其他網格(例如Delphi的TStringGrid)相比,它有點不尋常,因為使用Row和Column值不容易訪問網格的單元格。

最簡單的方法就是

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

它之所以有效,是因為TDBGrid的編碼方式,關聯的數據集已同步到當前選定/單擊的網格行。 一般來說,從數據集的當前記錄中獲取值是最容易的,但是您是這樣詢問的。 嘗試通過操作單元格的文本來避免更改當前記錄的值,因為DBGrid會在每一步上與您抗爭。

Fwiw,我已經看到了更多的“四處走動”的方式來獲取單元格文本,但是我更喜歡KISS原則。

請注意,一種更可靠的獲取單元格文本的方法如下:其中包括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