且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在运行时向clientdataset添加字段?

更新时间:2023-12-06 15:14:10

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

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

//添加现有字段
cds.FieldDefs.Update;
for i:= 0 to cds.FieldDefs.Count - 1 do
cds.FieldDefs [i] .CreateField(cds);

//添加计算字段
字段:= TStringField.Create(cds);
Field.FieldName:='city';
Field.Calculated:= True;
Field.DataSet:= cds;

cds.Open;
end;


另请参阅优秀文章 Cary Jensen


I have aTClientdataset, which is provided by a TTable’s dataset. The dataset has two fields: postalcode (string, 5) and street (string, 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.

I tried:

  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 is my clientdataset, Table1 is a paradox Table, but the problem is the same with other databases.

Thanks in advance

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;


Also see this excellent article by Cary Jensen.