Programming a Calculated Field
Go Up to Defining New Persistent Fields
After you define a calculated field, you must write code to calculate its value. Otherwise, it always has a null value. Code for a calculated field is placed in the OnCalcFields event for its dataset.
To program a value for a calculated field
- Select the dataset component from the Object Inspector drop-down list.
- Choose the Object Inspector Events page.
- Double-click the OnCalcFields property to bring up or create a CalcFields procedure for the dataset component.
- Write the code that sets the values and other properties of the calculated field as desired.
For example, suppose you have created a CityStateZip calculated field for the Customers table on the CustomerData data module. CityStateZip should display a company's city, state, and zip code on a single line in a data-aware control.
To add code to the CalcFields procedure for the Customers table, select the Customers table from the Object Inspector drop-down list, switch to the Events page, and double-click the OnCalcFields property.
The TCustomerData.CustomersCalcFields procedure appears in the unit's source code window. Add the following code to the procedure to calculate the field:
CustomersCityStateZip.Value := CustomersCity.Value + ', ' + CustomersState.Value + ' ' + CustomersZip.Value;
CustomersCityStateZip->Value = CustomersCity->Value + AnsiString(", ") +
Note: When writing the OnCalcFields event handler for an internally calculated field, you can improve performance by checking the client dataset's Using internally calculated fields in client datasets for details.