How to put
a Calculated field onto a Grid
by Peter Rorlick (the author is a co-founder of Montreal Business Software. He has been developing xbase solutions since 1981).

HERE'S a step-by-step example of how to create a calculated field and how to get that field to show up on a grid. (Note: a similar technique can be used to get calculated fields onto reports.)

Begin designing a new form. Using the navigator, switch to the \Samples\Fleet\Tables directory. Click on the Tables tab and drag and drop Aircraft.dbf onto your form. This will create a query object on the form, called Aircraft1.

Using the inspector, go the Events tab for the query object and click on the tool button of the OnOpen event.

In the function called Aircraft1_OnOpen, type:
oField=new Field()
oField.FieldName := "Make and model"
oField.BeforeGetValue := {; Return Trim(This.Parent["Make"].Value) + space(1) + This.Parent["Model"].Value }

You have just instructed the query to add a calculated field, showing Make and Model in a single column.

Note that you can sometimes create calculated fields more simply, in the SQL "SELECT...FROM..." statement. But the way we're doing it here is much more powerful, because the .BeforeGetValue is handled by VdB rather than by the SQL engine. This means that you can use xbase functions and UDFs to construct your calculated fields - and this is a vital difference. SQL is nice but it is sometimes not flexible enough.

From the Component Palette, drop a grid onto the form, and enlarge it. Select the grid, and using the inspector, click on the dropdown button of the DataLink property, and set it to Aircraft1.

 As soon as you do this, you'll notice that the grid becomes populated
with rows from the table.

Now, our goal is to get the calculated field onto the grid. To do this you will need to run the query again so that "Make and model" will be available in the Column Selector tool. Unfortunately, if you try to set the query's Active property to false and then back to true, you'll get an error. But you can effectively run the query again by saving the form (call it MyGrid.WFM) and then open it again with the designer. Once you have done that, click on the grid, bring up the inspector, and click on the tool button of the Columns property. Double-click on the "Make and model" field, and then double-click on the "Layout Image" field. Click on the OK button.

Save the form and run it. Voilà!