"Persistent fields" created at runtime make no sense. Creating persistent fields in the IDE allows them to be written to the .dfm for the form/datamodule, and then be created automatically when that .dfm is loaded from the executable, and can be accessed by name in your code that uses that datamodule.
If you're looking to not have to use FieldByName
at runtime, you can just do something like this:
TMyDataModule=class(TDataModule)
// Usual IDE created stuff, etc.
public
NameFld: TStringField;
LimitFld: TFloatField;
end;
procedure TMyDataModule.DataModuleCreate(Sender: TObject);
begin
NameFld := MyDataSet.FieldByName('CompanyName') as TStringField;
NameFld.Required := True;
LimitFld := MyDataSet.FieldByName('CreditLimit') as TFloatField;
LimitFld.Currency := True;
// Set other properties as needed.
end;
You now have the equivalent of persistent fields at runtime. They can be accessed as usual in other code that uses your datamodule.
procedure TMyDataModule.DoSomethingWithData(CompanyName: string; CreditLimit: Currency);
begin
MyDataSet.Edit;
NameFld.AsString := CompanyName;
LimitFld.AsCurrency := CreditLimit;
MyDataSet.Post;
end;
EDIT: Just thought of two exceptions to my statement "make no sense" - those would be calculated or lookup fields. For lookup fields, it's easiest to just add them to SQL via a JOIN
and let the server do it; for calculated fields, you can use the DataSet.FieldDefs.Add
and set the appropriate properties to name the field, set the newly created field's FieldType
to ftCalculated
, and assign an OnCalcFields
event handler to handle the calculation.