Search code examples
databasedelphidelphi-7calculated-field

Calculated fields in table


I'm trying to create a calculated field (Cost) in a database table for values entered by the user for example price and quantity like in the example below :

Cost = Price * Quantity

I searched but I couldn't find a clear way how to it.


Solution

  • Create a calculated field from the Field Editor.

    • Double click the TTable or TQuery to open the Fields Editor.
    • Right click the Fields Editor, and choose New Field from the popup menu (or press Ctrl+N).
    • In the New Field dialog, give the field a name (such as 'Cost') and type (perhaps Currency), and check the radio button for Calculated, and then click OK.
    • With the TTable or TQuery selected, choose the Events tab in the Object Inspector, find the OnCalcFields event, and double-click it to create the new empty event handler in the Code Editor.
    • Add something similar to the code below, adjusting as needed for your field names:

      procedure TCustForm.yourQueryCalcField(DataSet : TDataset);
      begin
        DataSet.FieldByName('Cost').AsCurrency :=  
              DataSet.FieldByName('Price').AsCurrency* 
              DataSet.FieldByName('Quantity').AsInteger;
      end;