开发者

Code to create Persistent Field components associated with TDataSet

开发者 https://www.devze.com 2023-03-16 13:11 出处:网络
Looking for som开发者_如何学Pythone example code illustrating how to create at runtime TField Components associated with a dataset.

Looking for som开发者_如何学Pythone example code illustrating how to create at runtime TField Components associated with a dataset.

In the IDE, if you plop down a dataset component, right-clicking brings up the fields editor that provides this functionality at design time. Have not been able to find code showing how to do it at runtime.

TIA


Each field type has a Create function that you pass the DataSet to that creates a field of that type and adds it to the Fields. From the help for DB.TStringField.Create.

var
  T: TStringField;
begin
  SQLDataSet1.Close;
  T := TStringField.Create(SQLDataSet1);
  T.FieldName := 'LastName';
  T.Name := SQLDataSet1.Name + T.FieldName;
  T.Index := SQLDataSet1.FieldCount;
  T.DataSet := SQLDataSet1;
  SQLDataSet1.FieldDefs.UpDate;
  SQLDataSet1.Open;
end;


"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.

0

精彩评论

暂无评论...
验证码 换一张
取 消