database - 如何使用 OnCellClick 事件在 Delphi 中的 DBGrid 上获取单元格的内容
问题描述
如何通过单击表单上 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 原则。
请注意,获取单元格文本的一种更可靠的方法如下:
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;
推荐阅读
- android - Android Studio 未知的 Unicode 字体?
- mysql - 在 sum 内计数时,按功能分组无效
- c# - 在数据库每分钟获取新数据的同时从数据库加载更多数据
- c# - 将xml复制到没有标题的新文件
- reactjs - 中继 RefetchContainer 不更新道具
- node.js - 在传出请求快递js中使用中间件
- apache - 如何在 Apache 上使用 htaccess 和 mod_headers.c 发送带有 x-robots 标签 noindex 的 http 标头
- python - 在 Python 中使用 Redis 将数据保存在内存中的最快方法
- javascript - 显示另一个弹出窗口时如何隐藏 Bootstrap 3 弹出窗口?
- php - 将字符串转换为数组,然后在将过滤器链接添加到每个单词后打印数组以看起来像原始字符串