Add field to table at runtime

Posted in Databases

Use standard methods and properties (FieldName, DataSet and ect.) of table component.

procedure TForm1.Button1Click(Sender: TObject);
var
  Field: TField;
  i: Integer;
begin
  Table1.Active:=False;
  for i:=0 to Table1.FieldDefs.Count-1 do
    Field:=Table1.FieldDefs[i].CreateField(Table1);

  Field:=TStringField.Create(Table1);
  with Field do
  begin
    FieldName:='New Field';
    Calculated:=True;
    DataSet:=Table1;
  end;
  Table1.Active:=True;
end;