Has anyone noticed this bit of code?
procedure TSampleForm.btnOpenClick(Sender: TObject); begin if dsSample.Active then dsSample.Close; dsSample.SQL.text:='select id,state,oldstate,"" as txtState,"" as txtOldState from states where active=1'; dsSample.Open; end;
It does not change the database field to a calculated field ... It changes an unnecessary field to a calculated field. He knows the type of field ... it will be a string ... So this is a big deal ... No ... This is a hack ... Yes ... You can do the same in SQL using Cast ... Actually I have never seen a reason to use Calculated Fields ... I usually make the same thing easier in SQL.
I added more information after a little work, why not do it ...
sabri.arslan code ... for creating fields ... from FieldList ... also has problems with the lack of key settings and processing of hirchi fields.
dmp:=DataSet.FieldDefs.Items[i].FieldClass.Create(self);
Then we have Francois ...
if you call the none hacked code you get this... for I := 0 to MyQuery.FieldDefList.Count - 1 do with MyQuery.FieldDefList[I] do if (DataType <> ftUnknown) and not (DataType in ObjectFieldTypes) and not ((faHiddenCol in Attributes) and not MyQuery.FIeldDefs.HiddenFields) then CreateField(Self, nil, MyQuery.FieldDefList.Strings[I]);
umm ... Missing SetKeyFields will lead to unexpected behavior? Also, if the ObjectView property is set to True ... your dataset will not behave correctly for hierarchical fields ... It looks safer to just call Hack to CreateFields than use its code ... except that you have to be sure that your dataset component never calls this code ...
CreateField calls CreateFieldComponent and you get the result: = FieldClassType.Create (Owner) for your TField
Adapted from Borland's help TFieldDef "A field definition has a corresponding TField object, but not all TField objects have a corresponding field definition. For example, computed fields do not have field definition objects."
So, I ask you ... are you sure you can’t imagine the unknown behavior by creating CalculatedField on the fly? Are you sure that the fields have not yet been created or will not be created later? (There is an error in the sabri.arslan code because it opens / after opening ... It overwrites the original TFields ... I don’t understand why we need to recreate TField for an already open dataset)
So, what happens when CreateFields is called by a dataset (BDE and ADO do this on InternalOpen and make sure they are not values in Fields ... all Dataset components do this the way? They don’t have to). What happens to the fields that you have already created ... are they overwritten? I did not see any code in TDataset or TFieldDef that checked whether TField was already created for the corresponding TFieldDef other than check the DefaultFields box (if the fields have a value).