Search code examples
delphidelphi-xe2tclientdataset

How do I destroy run-time defined TClientDataSet TFields?


I have a TClientDataSet coupled to a query with all fields defined in the Fields editor.

At runtime I add three fkInternalCalc fields:

class procedure TTaskIndexCalculator.Setup(AClientDataSet: TClientDataSet);
var
   lCalcIntField : TIntegerField;
   lCalcStrField : TStringField;
begin
   CDS := AClientDataSet;
   CDS.DisableControls;
   CDS.Close;
   lCalcIntField := TIntegerField.Create(CDS);
   with lCalcIntField do
   begin
      Name := 'CalcFldLevel';
      FieldKind := fkInternalCalc;
      FieldName := 'TT_LEVEL';
      DataSet := CDS;
   end;
   lCalcIntField := TIntegerField.Create(CDS);
   with lCalcIntField do
   begin
      Name := 'CalcFldDateOrder';
      FieldKind := fkInternalCalc;
      FieldName := 'TT_DATEORDER';
      DataSet := CDS;
   end;
   lCalcStrField := TStringField.Create(CDS);
   with lCalcStrField do
   begin
      Name := 'CalcFldSortString';
      FieldKind := fkInternalCalc;
      FieldName := 'TT_SORTSTRING';
      Size := 200;
      DataSet := CDS;
   end;
   CDS.Open;
end;

I do some calculations using these additional fields, update a 'real' field, then I'm done:

class procedure TTaskIndexCalculator.TearDown;
begin
   with CDS do
   begin
      Close;
      Fields[CDS.FieldCount-1].Free;
      Fields[CDS.FieldCount-1].Free;
      Fields[CDS.FieldCount-1].Free;
      Filter := '';
      Filtered := false;
      Open;
      EnableControls;
   end;
end;

However, on the final 'Open' statement I get a 'not found' error for the TT_SORTSTRING field (probably the other two are wrong as well).

The TClientDataSet is connected to a TDBGrid.

What am I doing wrong in removing the three fields (or earlier)?

Reading the excellent Cary Jensen article did not help me; I have a mixed situation of design-time and run-time fields.


Solution

  • Awwww, one of these things ;-)

    Not only did I play with the filter settings during the calculations, but also with property IndexFieldNames. And the last IndexFieldNames content contained TT_SORTSTRING.
    My TearDown routine has to reset that too:

    IndexFieldNames := '';