Delphi - Change Fields definitions of a TClientDataSet that has data

这一生的挚爱 提交于 2020-01-06 14:05:51

问题


I'm creating FieldDefs at runtime for a TClientDataSet. Still at runtime I want to remove all FieldDefs. I'm saving TClientDataSet physically to a disc file. I tried removing existing FieldDefs using the following code so I could add new ones. But it didn't work:

with fDataSet do begin
    Active := False;
    DisableControls;
    FieldDefs.Clear;
    Fields.Clear;
    EnableControls;
end;

After executing this code, FieldDefs and Fields count are 0, but if I close and reopen the disc file, FieldDefs and Fields are still there.

What is the right way to change FieldDefs and Fields?


回答1:


Consecutive Open recreates fields from internal Dataset. Just clear old field defs, add new ones and recreated dataset:

...
CDS.FieldDefs.Clear;
CDS.Fields.Add(...);
...
CDS.Fields.Add(...);
CDS.CreateDataSet;
...



回答2:


You'll have to pump the data from the old data set structure into the new along the following lines:

  • Define a new client dataset with the new structure.
  • Open your old client data set.
  • Iterate the old data set, and insert a record in the new one, performing any calculations and default assignments as you go.

E.g.

while not FOldDataSet.Eof do
begin
  FNewDataSet.Insert;
  FNewDataSet['FIELD1'] := FOldDataSet['FIELD3'];
  FNewDataSet['FIELD2'] := CDefaultFIELD2;
  FNewDataSet.Post;

  FOldDataSet.Next;
end;


来源:https://stackoverflow.com/questions/21293186/delphi-change-fields-definitions-of-a-tclientdataset-that-has-data

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!