我有一个数据集TclientDataSet,其中的字段是由代码创建的。 我需要用户在保留现有数据的同时附加其他字段。
`MYclientDataSet.FieldDefs.Add(s, ftString, 20);
MYclientDataSet.CreateDataset;
MYclientDataSet.Open;
MYclientDataSet.edit;
MYclientDataSet.FieldByName(s).AsString := 'Test';
MYclientDataSet.post;`
这有效,但CreateDataset会删除所有数据。 有没有办法将新字段添加到数据集中?
我尝试了很多其他解决方案,但似乎都没有工作
非常感谢答案 0 :(得分:5)
You can achieve this with the following code, which basically saves the current data, creates the new field structure and copies the saved data back:
var
cds: TClientDataSet;
begin
cds := TClientDataSet.Create(nil);
try
cds.Data := MyClientDataSet.Data;
MyClientDataSet.Close;
MyClientDataSet.FieldDefs := cds.FieldDefs;
MyClientDataSet.FieldDefs.Add('Note', ftString, 20);
MyClientDataSet.CreateDataSet;
cds.First;
while not cds.Eof do begin
MyClientDataSet.Append;
MyClientDataSet.CopyFields(cds);
MyClientDataSet.FieldByName('Note').AsString := 'Test';
MyClientDataSet.Post;
cds.Next;
end;
finally
cds.Free;
end;
end;
答案 1 :(得分:1)
If you are asking about fields of type fkData
, i.e. ones which would be included in the CDS's saved data, you cannot add such fields once the CDS is already open.
The simplest way I know of to achieve the equivalent effect is to
Save the CDS data to XML.
Modify the metadata in the XML which defines the fkData fields, to add the ones you want.
Save the XML.
Reload the CDS from the XML.
I think I posted an example of how to do this in a reply to an SO q a while ago. If I can find it, I'll add a link to it later on.