Based on How to add a field programatically to a TAdoTable in Delphi I am trying to add all the fields dynamically to a FibPlus dataset (could be any TDataSet descendant). Each field is declared as a variable. Declarations part
TForm4 = class(TForm)
pFIBDatabase1: TpFIBDatabase;
pFIBTransaction1: TpFIBTransaction;
ds1: TpFIBDataSet;
DataSource1: TDataSource;
DBGrid1: TDBGrid;
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
iVERField : TFIBIntegerField;//I need that all fields to be represented by a variable
{ Public declarations }
end;
and on the formcreate event, I create all the fields, set the needed properties and add dynamically all of them to the my dataset.
procedure TForm4.FormCreate(Sender: TObject);
var i:Integer;
fieldDef :TFieldDef;
begin
ds1.SQLs.SelectSQL.Text := 'select ver from ver';
ds1.Fields.Clear;
ds1.FieldDefs.Clear;
ds1.FieldDefs.update;
iVERField := TFIBIntegerField.Create(ds1);
iVERField.FieldName := 'VER';
iVERField.DisplayLabel := 'VER';
iVERField.Name := 'iVERField';
iVERField.DataSet := ds1;
ds1.Fields.Add(iVERField);
ds1.Open;
end;
My problem is that the field appear as a duplicate on a dbgrid
LE: Why field appears twice:
iVERField.DataSet := ds1; //one
ds1.Fields.Add(iVERField);//two
LE1: Is this the way I should add all the fields as variables to the dataset?
In D7 (and I doubt it's changed since), TField's SetDataSet method already calls the Ffields.Add method of the dataset, so your explicit ds1.Fields.Add adds it a second time, hence the duplicated field.