问题
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