I want to add a calulated field at runtime to a query supplied by a user (I have no idea of what fields/columns are in the query before hand)
My current code is
UniQuery2->Prepare();
field_def = UniQuery2->FieldDefs->AddFieldDef();
field_def->DataType = ftInteger;
field_def->Name = "calc";
for(int f = 0; f < UniQuery2->FieldDefs->Count; f++)
{
field_def = UniQuery2->FieldDefs->Items[f];
CodeSite->Send(" " + field_def->Name);
field = field_def->CreateField(UniQuery2);
if(field->FieldName == "calc")
field->FieldKind = fkCalculated;
}
//CodeSite - lists four fields, including my "calc" field
UniQuery2->Open();
for(int f = 0; f < UniQuery2->FieldDefs->Count; f++)
{
field_def = UniQuery2->FieldDefs->Items[f];
CodeSite->Send(" " + field_def->Name);
}
// codesite shows only three fileds, my calc field is missing!!
what am I doing wrong?
Thanks
Adding a calculated field
Re: Adding a calculated field
Hello,
There is a code below for adding calculated field in run-time and calculation of this field value.
There is a code below for adding calculated field in run-time and calculation of this field value.
Code: Select all
type
TForm1 = class(TForm)
...
procedure UniQuery1CalcFields(DataSet: TDataSet);
private
FCalc: TIntegerField;
....
end;
procedure TForm1.FormCreate(Sender: TObject);
var
i: integer;
begin
UniQuery1.FieldDefs.Update;
for i := 0 to UniQuery1.FieldDefs.Count - 1 do
UniQuery1.FieldDefs[i].CreateField(UniQuery1);
FSUM := TIntegerField.Create(UniQuery1);
FSUM.FieldName := 'Calc';
FSUM.FieldKind := fkCalculated;
FSUM.DataSet := UniQuery1;
UniQuery1.Open;
end;
procedure TForm1.UniQuery1CalcFields(DataSet: TDataSet);
begin
FCalc.Value := 124;
end;
Re: Adding a calculated field
Thanks Alex
That doesn't work for me,
I created a test program and connected to a test database (with two fields in my case (name and address)
I then ran the following code
The final step of the code only listed the original two fileds, not the new "calc" field.
What am I doing wrong?
Thank You.
That doesn't work for me,
I created a test program and connected to a test database (with two fields in my case (name and address)
I then ran the following code
Code: Select all
TIntegerField *field;
UniQuery1->SQL->Clear();
UniQuery1->SQL->Add("select * from test");
UniQuery1->FieldDefs->Update();
for(int f = 0; f < UniQuery1->FieldDefs->Count; f++)
{
UniQuery1->FieldDefs->Items[f]->CreateField(UniQuery1);
}
field = new TIntegerField(UniQuery1);
field->FieldName = "calc";
field->FieldKind = fkCalculated;
field->DataSet = UniQuery1;
UniQuery1->Open();
for(int f = 0; f < UniQuery1->FieldDefs->Count; f++)
{
Memo2->Lines->Add(UniQuery1->FieldDefs->Items[f]->Name);
}
What am I doing wrong?
Thank You.
Re: Adding a calculated field
FieldDef are not created for Hidden fields and fields with FieldKind <> fkData .
Re: Adding a calculated field
If you have any further questions, feel free to contact us.