Code to create Persistent Field components associated with TDataSet

走远了吗. 提交于 2019-12-24 03:08:19

问题


Looking for some 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


回答1:


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;



回答2:


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



来源:https://stackoverflow.com/questions/6526832/code-to-create-persistent-field-components-associated-with-tdataset

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!