Borland®
Shop
Products Downloads Services Support Partners News & Events Company Community
Delphi
Documentation
Support

Additional Resources
Technology Partners
Books
Community

 Dynamic Creation of a Table

This example dynamically creates TFieldDefs, TFields, calculated fields, a table, a TTable, and attaches an event handler to the OnCalc event.

	
unit Gridcal;
interface
uses  SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls,
  Forms, Dialogs, StdCtrls, DBTables, DB, Grids, DBGrids;
type
  TForm1 = class(TForm)
    Button1: TButton;
    procedure MyCalcFields(DataSet: TDataset);
    procedure NewTable(MyDataBaseName, MyTableName: string;
      var MyTable: TTable; MyDataSource: TDataSource; MyGrid: TDBGrid);
    procedure FormCreate(Sender: TObject);
  public
    t1, t2: TTable;
    tsrc1, tsrc2: TDataSource;
    grd1, grd2: TDBGrid;
    MyCalcField :TFloatField;
  end;
var
  Form1: TForm1;
implementation
{$R *.DFM}
procedure TForm1.MyCalcFields(DataSet: TDataset);
begin
  with DataSet do
    FieldByName(MyCalcField.Name).AsFloat :=
      FieldByName('Field1').AsFloat * FieldByName('Field2').AsFloat;
end;
procedure TForm1.NewTable(MyDataBaseName, MyTableName: string;
  var MyTable: TTable; MyDataSource: TDataSource; MyGrid: TDBGrid);
begin
  MyTable := TTable.Create(Self);
  with MyTable do begin
    DatabaseName := MyDatabaseName;
    TableName := MyTableName;
    TableType := ttParadox;
    AutoCalcFields := True;
    OnCalcFields := MyCalcFields;
    with FieldDefs do begin
      Clear;
      Add('Field1', ftFloat, 0, false);
      FieldDefs[0].CreateField(MyTable);
      Add('Field2', ftFloat, 0, false);
      FieldDefs[1].CreateField(MyTable);
      Add('Field3', ftFloat, 0, false);
      FieldDefs[2].CreateField(MyTable);
    { create a calculated TField }
      MyCalcField := TFloatField.Create(MyTable);
      with MyCalcField do begin
        FieldName := 'MyCalcField';
        Calculated := True;
        Visible := True;
        DataSet := MyTable;
        Name := MyTable.Name + FieldName;
        MyTable.FieldDefs.Add(Name, ftFloat, 0, false);
      end;
    end;
    MyTable.CreateTable;
  end;
  MyDataSource := TDataSource.Create(Self);
  MyDataSource.DataSet := MyTable;
  MyGrid := TDBGrid.Create(Self);
  with MyGrid do begin
    Parent := Self;
    Align := alTop;
    DataSource := MyDataSource;
  end;
  MyTable.Active := True;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
  NewTable('DBDEMOS', 'MyTable1', t1, tsrc1, grd1);
end;
end.

DISCLAIMER: You have the right to use this technical information subject to the terms of the No-Nonsense License Statement that you received with the Borland product to which this information pertains.

 
Site Map Search Contact