Delphi How To: Creating Calculation Field

Wednesday, June 11, 2008

In this Delphi Tutorial i will explain how to create a calculation field on Delphi DBAware component and show it on the DBGrid. Calculation Field is an additional field that we can create to do automatic calculation at OnCalcFields event.



For example you have a table called SalesDetail that have the following structure :


Table Structure

if you want your Application to do automatic calculation for the total price (UnitPrice * Quantity) as you insert or edit Data, you can follow this steps :




1. Creating Calculation Field On TADOTable Component



  • Add TADOTable Component to a Form

  • Set its ConnectionString and TableName properties so its connected to your Database

  • Right click on the TADOTable component and choose Fields Editor... the Fields Editor will appear

  • Right click on the Fields Editor and choose Add All Fields to include all field in the Table

  • Right Click on Fields Editor and choose New Field... the New Field Dialog will appear

  • Enter a name for this new field in the Name textbox for example CTotal

  • Choose Number Data Type (Integer, Float, Largeint, etc depend on posible value range you will need) on Type combobox

  • Choose Calculated in the Field Type Section and then click the OK button






  • Now you have created a calculation Field called CTotal








2. Adding Code to your Application to do Automatic Calculation



  • Add a DataSource component to the form and connect it to your TTable or TADOTable Component.

  • Add a DBGrid component to the form and connect it to your DataSource Component

  • set the AutoCalcFields Properties of TADOTable Component to True.

  • To do automatic calculation as you insert or edit Data, add this code on OnCalcFields event of TADOTable component

  • AdoTable1.FieldValues['CTotal'] :=

    AdoTable1.FieldValues['UnitPrice'] * AdoTable1.FieldValues['Qty'];




Designtime


Application Designtime


Runtime


Application Runtime



Download Sourcode here

0 comments:

Recent Comments

Tags Cloud

Blogumulus by Roy Tanck and Amanda Fazani