Icon Calculated Columns

As discussed in the Creating and Loading DataSets topic, dataset columns are normally defined automatically when dragging a dataset from the server manager in the IDE and dropping the dataset on a form, request handler, or database designer surface, or they can be loaded at runtime from the web server via the TDatabase LoadColumns method.

However, in some cases you may want to define columns that derive their contents from a calculation. These types of columns are, of course, called calculated columns. Creating a calculated column is very simple:
  • Create the column as you normally would, using the Add method of the TDataSet Columns.


  • Set the new column's Calculated property to True.


  • Define an event handler for the TDataSet OnCalculateRow event that executes the calculation code and assigns a value to the new calculated column.
Whenever a column in a row is updated, the OnCalculateRow event handler will be triggered so that any calculated columns can be re-computed for that row.

Any editable controls bound to a calculated column will automatically be read-only.

The following is an example of creating a calculated column that shows concatenated information from two other columns in the dataset:

procedure TForm1.Form1Create(Sender: TObject);
begin
   with Albums.Columns.Add do
      begin
      Name:='ArtistYear';
      DataType:=dtString;
      Length:=60;
      Calculated:=True;
      end;
   Albums.OnCalculateRow:=AlbumsCalculateRow;
end;

procedure TForm1.AlbumsCalculateRow(Sender: TObject; Column: TDataColumn);
begin
   Albums.Columns['ArtistYear'].AsString:=Albums.Columns['Artist'].AsString+
            ' ('+Albums.Columns['Year'].AsString+')';
end;

Information Do not attempt to programmatically modify a calculated column outside of an OnCalculateRow event handler. Attempting to do so will result in an error. Also, you cannot modify non-calculated columns in an OnCalculateRow event handler.
Image