The If
expression is one of the most useful control structures. It allows you to evaluate an expression if a condition is true and evaluate a different expression otherwise.
Note: The correct Crystal syntax for If statements is if <condition> then <then> else <else>, where <condition>, <then>, and <else> are all single expressions. If you have multiple expressions after the <then> or <else>, convert them into single expressions by surrounding them in parentheses. For example:
Global stringVar lastValue;
if {Branch_View.Branch_ID} = lastValue
then
(lastValue := {Branch_View.Branch_ID};
crRed;)
else
(lastValue := {Branch_View.Branch_ID};
crBlack;)
Note:
When formatting with conditional formulas, always include the Else keyword; otherwise, values that don't meet the If condition may not retain their original format. To prevent this, use the DefaultAttribute function (If...Else DefaultAttribute).
When creating record selection formulas that include If expressions, always include the Else keyword; otherwise, no records or unexpected records may be returned. For example, a record selection such as If {parameter field} = "less than 100" then {field} < 100" evaluates as False and returns no records. To correct this problem, complete the formula with Else True.
Example
A company plans to pay a bonus of 4 percent to its employees except for those who work in Sales who will receive 6 percent. The following formula using an If expression would accomplish this:
//If example 1
If {Employee.Dept} = "Sales" Then
{Employee.Salary} * 0.06
Else
{Employee.Salary} * 0.04
In this example, if the condition {Employee.Dept} = "Sales" evaluates as true, then the
{Employee.Salary} * 0.06
expression is processed. Otherwise the expression following the Else, namely the
{Employee.Salary} * 0.04
is processed.
Suppose another company wants to give employees a 4% bonus, but with a minimum bonus of $1,000. The following example shows how. Notice that the Else
clause is not included; it is optional, and not needed in this case.
//If example 2
Local CurrencyVar bonus := {Employee.Salary} * 0.04;
If bonus < 1000 Then
bonus := 1000;
//The final expression is just the variable 'bonus'.
//This returns the value of the variable and is the
//result of the formula
bonus
Another way of accomplishing example 2 is to use an Else clause:
//If example 3
Local CurrencyVar bonus := {Employee.Salary} * 0.04;
If bonus < 1000 Then
1000
Else
bonus
Now suppose that the previous company also wants a maximum bonus of $5,000. You now need to use an Else If clause. The following example has only one Else If clause, but you can add as many as you need. Note, however, that there is a maximum of one Else clause per If expression. The Else clause is executed if none of the If or Else If conditions are true.
//If example 4
Local CurrencyVar bonus := {Employee.Salary} * 0.04;
If bonus < 1000 Then
1000
Else If bonus > 5000 Then
5000
Else
bonus