创建与 TDataSet 关联的持久字段组件的代码
寻找一些示例代码,说明如何在运行时创建与数据集关联的 TField 组件。
在 IDE 中,如果您放下数据集组件,右键单击会弹出字段编辑器,该编辑器在设计时提供此功能。无法找到显示如何在运行时执行此操作的代码。
TIA
Looking for some example code illustrating how to create at runtime TField Components associated with a dataset.
In the IDE, if you plop down a dataset component, right-clicking brings up the fields editor that provides this functionality at design time. Have not been able to find code showing how to do it at runtime.
TIA
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
每个字段类型都有一个 Create 函数,您将 DataSet 传递给该函数,该函数将创建该类型的字段并将其添加到 Fields 中。来自 DB.TStringField.Create 的帮助。
Each field type has a Create function that you pass the DataSet to that creates a field of that type and adds it to the Fields. From the help for DB.TStringField.Create.
在运行时创建的“持久字段”没有任何意义。在 IDE 中创建持久字段允许将它们写入表单/数据模块的 .dfm,然后在从可执行文件加载 .dfm 时自动创建它们,并且可以通过使用该数据模块的代码中的名称进行访问。
如果您希望在运行时不必使用
FieldByName
,则可以执行以下操作:您现在在运行时拥有相当于持久字段的功能。可以像往常一样在使用数据模块的其他代码中访问它们。
编辑:只是想到了我的陈述“没有意义”的两个例外 - 那些将是计算字段或查找字段。对于查找字段,最简单的方法是通过 JOIN 将它们添加到 SQL 中,然后让服务器执行此操作;对于计算字段,您可以使用
DataSet.FieldDefs.Add
并设置适当的属性来命名字段,将新创建字段的FieldType
设置为ftCalculated
code>,并分配一个OnCalcFields
事件处理程序来处理计算。"Persistent fields" created at runtime make no sense. Creating persistent fields in the IDE allows them to be written to the .dfm for the form/datamodule, and then be created automatically when that .dfm is loaded from the executable, and can be accessed by name in your code that uses that datamodule.
If you're looking to not have to use
FieldByName
at runtime, you can just do something like this:You now have the equivalent of persistent fields at runtime. They can be accessed as usual in other code that uses your datamodule.
EDIT: Just thought of two exceptions to my statement "make no sense" - those would be calculated or lookup fields. For lookup fields, it's easiest to just add them to SQL via a
JOIN
and let the server do it; for calculated fields, you can use theDataSet.FieldDefs.Add
and set the appropriate properties to name the field, set the newly created field'sFieldType
toftCalculated
, and assign anOnCalcFields
event handler to handle the calculation.