如何在运行时向客户端数据集添加字段?字段、客户端、数据、如何在

由网友(情定三生)分享简介:我有一个 TClientDataSet,它由 TTable 的数据集提供.数据集有两个字段:postalcode(string, 5) 和 street(string, 20)I have a TClientDataSet, which is provided by a TTable’s dataset.The d...

我有一个 TClientDataSet,它由 TTable 的数据集提供.数据集有两个字段:postalcode(string, 5) 和 street(string, 20)

I have a TClientDataSet, which is provided by a TTable’s dataset. The dataset has two fields: postalcode (string, 5) and street (string, 20)

在运行时我想显示第三个字段(字符串,20).该字段的例程是获取邮政编码作为参数,并返回属于该邮政编码的城市.

At runtime I want to display a third field (string, 20). The routine of this field is getting the postalcode as a parameter and gives back the city belongs to this postalcode.

问题只是将计算字段添加到已经存在的字段.填充数据本身不是问题.

The problem is only about adding a calculated field to the already existing ones. Filling the data itself is not the problem.

我试过了:

  cds.SetProvider(Table1);
  cds.FieldDefs.Add('city', ftString, 20);

  cds.Open;

  cds.Edit;
  cds.FieldByName('city').AsString := 'Test';  // --> errormessage (field not found)
  cds.Post;

cds是我的clientdataset,Table1是悖论表,但是其他数据库的问题是一样的.

cds is my clientdataset, Table1 is a paradox Table, but the problem is the same with other databases.

提前致谢

推荐答案

如果要添加基础数据之外的其他字段,还需要手动添加现有字段.添加字段时需要关闭数据集,但如果您不想手动跟踪所有字段详细信息,则可以使用 FieldDefs.Update 获得必要的元数据.基本上是这样的:

If you want to add additional fields other than those exist in the underlying data, you need to also add the existing fields manually as well. The dataset needs to be closed when you're adding fields, but you can have the necessary metadata with FieldDefs.Update if you don't want to track all field details manually. Basically something like this:

var
  i: Integer;
  Field: TField;
begin    
  cds.SetProvider(Table1);

  // add existing fields
  cds.FieldDefs.Update;
  for i := 0 to cds.FieldDefs.Count - 1 do 
    cds.FieldDefs[i].CreateField(cds);

  // add calculated field
  Field := TStringField.Create(cds);
  Field.FieldName := 'city';
  Field.Calculated := True;
  Field.DataSet := cds;

  cds.Open;
end;

另请参阅 优秀文章 卡里詹森.

阅读全文

相关推荐

最新文章