2

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

enter image description here

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?

Community
  • 1
  • 1
RBA
  • 12,337
  • 16
  • 79
  • 126

1 Answers1

3

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.

MartynA
  • 30,454
  • 4
  • 32
  • 73
  • Sorry, I thought when you said "LE: Why field appears twice: [...]" you were asking why "ds1.Fields.Add(iVERField);" adds a second instance of the field. If you didn't mean that, what did you mean (I'm asking so someone might give you a better answer)? But anyway, minus that step, yes that's how you can add instance variables for each field, setting the fields' FieldKind as necessary. – MartynA Jan 30 '14 at 14:53
  • Thank you for pointing this out. As per commented code it is obvious when first and second fields appear. I should be more explicit.At the same time I've added a LE1 which clears enough first LE – RBA Jan 30 '14 at 17:19