Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add fields to a clientdataset at runtime?

I have a TClientDataSet, 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

like image 856
CloudyMarble Avatar asked Feb 08 '11 14:02

CloudyMarble


2 Answers

You should use CreateDataset after add field:

cds.SetProvider(Table1);
cds.FieldDefs.Add('city', ftString, 20);
cds.CreateDataset; 

cds.Open;
cds.Edit;
cds.FieldByName('city').AsString := 'Test';  
cds.Post;
like image 112
Morteza Esmizadeh Avatar answered Sep 22 '22 15:09

Morteza Esmizadeh


Well i found a simpler solution, as i have 24 fields in my sql i didnt wanted to add them all manually so i added a dummy field to the sql statement instead like:

select '      ' as city, the rest of the fields ... 

which i can modify in my program OnAfterOpen event.

Well i had to define in the sql how long that field should be by leaving enough empty spaces, for instance 5 empty spaces for 5 characters, so i must know how long the city name could be.

like image 45
CloudyMarble Avatar answered Sep 22 '22 15:09

CloudyMarble