Skip to main content
All docs
V24.1

How to Construct Expressions

  • 6 minutes to read

This topic lists solutions to common tasks related to expression construction.

Create Expression at Runtime

An expression enables you to specify a property value for a control or a parameter.

To create an expression binding for a report control, create an ExpressionBinding object, specify its properties, and add the ExpressionBinding object to the XRControl.ExpressionBindings collection.

The ExpressionBinding constructor needs the following arguments:

EventName
The name of the event whose handler evaluates the expression. Typically you should set this property to the “BeforePrint” (the BeforePrint event) or “PrintOnPage” (the PrintOnPage event) string. If you omit this property, the expression is evaluated in the BeforePrint event. You can use the [Arguments.PageIndex] value to get the current page index in the expression evaluated in the PrintOnPage event.
PropertyName
The property to which the expression applies.
Expression
A binding expression that is parsed and processed to specify a control or parameter’s property value.

The following code snippet specifies an expression for a control’s property:

using DevExpress.XtraReports.UI;

public partial class XtraReport1 : DevExpress.XtraReports.UI.XtraReport {
    public XtraReport1() {
        InitializeComponent();

        XRLabel label = new XRLabel();
        this.Report.Bands[BandKind.Detail].Controls.Add(label);
        label.LeftF = 100;
        label.TopF = 100;
        // Specify an expression that sets the label's Text to the current date. The expression is rendered within the BeforePrint event.
        label.ExpressionBindings.Add(new ExpressionBinding("Text", "TODAY()"));
        // Specify an expression that makes the text bold on the first page.
        label.ExpressionBindings.Add(new ExpressionBinding("PrintOnPage", "Font.Bold", "Iif([Arguments.PageIndex] == 0, true, false)"));
    }
}

The following code specifies a custom expression for the label’s XRControl.Text property. The code assumes that the report is bound to a data source with UnitPrice and UnitsInStock fields.

using DevExpress.XtraReports.UI;

public XtraReport1() {
    // ...
    ExpressionBinding expressionBinding = new ExpressionBinding("BeforePrint", "Text", "[UnitPrice]*[UnitsInStock]");
    xrLabel1.ExpressionBindings.Add(expressionBinding);
}

Review the following topic for more information: Data Binding Modes.

Format Values in Expression

Review the following help topic for more information: Functions for Expression Bindings and Calculated Fields.

Calculate Group Summaries

Use the ^ operator to specify an expression that calculates a group summary.

  • Sum up the EFC field values in a group:

    [][[GroupFieldName] == [^.GroupFieldName]].Sum([EFC])
    
  • Specify the group header value:

    [][[CategoryID] == [^.CategoryID] and [ProductID] == [][[CategoryID] == [^.CategoryID]].Max([ProductID])].Max([ProductName])
    
  • Count the number of times a value occurs:

    The following expression counts how many times the value 12 occurs in the data source:

    [][[FootSize]='12'].Count()
    

    The following expression counts the number of records with non-zero values:

    [][[FootSize]!=0].Avg([FootSize])
    

Calculate a Percentage of Aggregate Values

Use the appropriate conversion function (ToFloat in this example) to get the correct result of the division operation when calculating percentages:

ToFloat([].Sum([UnitPrice]*[Quantity]*(1-[Discount])) / [].Sum([UnitPrice]*[Quantity]))

Reference Report Items

The Report Explorer window displays report elements. You can access these elements and their properties in an expression. Specify the following expression for the label’s Background Color property to set it to the BackColor property of xrLabel2:

[ReportItems].[xrLabel2].[BackColor]

[ReportItems] is a plain list that includes all report items.

Note that you cannot use the ReportItems collection in a Calculated Field‘s expression.

Note

You should reference report item values with caution. We do not guarantee that by the time an expression is parsed, the item referenced in an expression is already displayed and has the correct value.

Specify Images for Picture Boxes

When you specify an expression for the XRPictureBox.ImageSource property, you can use image identifiers from the XtraReport.ImageResources collection:

IIf([MarchSales]>20, [Images.ArrowUp],[Images.ArrowDown])

Use Row/Column Indexes for Cross Tab Cells

Use the following variables to change the XRCrossTab cell appearance:

Variable

Description

Example

Arguments.GroupColumnIndex

Returns the index of a cell’s column within a group.

Iif([Arguments.GroupColumnIndex] % 2 == 1, Rgb(235, 241, 252), ?)

Result: Alternating colors are applied to the XRCrossTab for odd and even columns.

Arguments.GroupRowIndex

Returns the index of a cell’s row within a group.

Iif([Arguments.GroupRowIndex] % 2 == 1, Rgb(235, 241, 252), ?)

Result: Alternating colors are applied to the XRCrossTab for odd and even rows.

You can specify expressions that are evaluated when the XRControl.BeforePrint and XRControl.PrintOnPage events occur.

Use the following variables to specify an expression calculated in the XRControl.BeforePrint event handler:

Variable

Description

Example

DataSource.RowCount

Returns the total number of data rows in a data source.

[DataSource.RowCount] != 0

Result: When this expression is applied to a control’s Visible property, the control is hidden if the data source contains no data.

DataSource.CurrentRowIndex

Returns an index of the current data row in a data source.

Iif([DataSource.CurrentRowIndex] % 2 = 0, 'red', 'green')

Result: When this expression is used for a table row’s BackColor property, odd rows are colored in red, even rows are colored in green.

DataSource.CurrentRowHierarchyLevel

Returns the zero-based level of the current row in a hierarchical report.

Iif([DataSource.CurrentRowHierarchyLevel] == 0, Rgb(231,235,244), ?)

Result: When this expression is used for the BackColor property of the DetailBand band that is printed in tree mode, the root level rows are highlighted.

Use the following variables to specify an expression calculated in the XRControl.PrintOnPage event handler:

Variable

Description

Example

Arguments.PageIndex

Returns an index of the currently generated report document page.

[Arguments.PageIndex] % 2 = 0

Result: The control is displayed on odd pages only when this expression is used for a control’s Visible property.

Arguments.PageCount

Returns the page count in a report document.

Do not use the Arguments.PageCount field in the following scenarios, as its value may be incorrect:

Iif(([Arguments.PageIndex] = [Arguments.PageCount] - 1), 'The last page!', '')

Result: When this expression is applied to a label’s Text property, the The last page! string is displayed on the last page.

Do not use the Arguments.PageIndex and Arguments.PageCount variables in the following scenarios, as these properties are not set to correct values:

Specify Parent Relations

Use the ‘^’ parent relation operator to refer to a parent in expressions that are written in the context of a child. You can apply this operator successively to span multi-level parent relationships.

You can use this operator to refer to the currently processed report group. This allows you to calculate aggregates within groups, as shown in the following expression:

[][[^.CategoryID] == [CategoryID]].Sum([UnitPrice])

View Example: How to use aggregate functions in Calculated Field expressions

Test Collection Elements

Use brackets to check if a collection contains an element that meets a condition. The following expression returns true if the Accounts collection contains at least one element that meets the [Amount] == 100 condition:

[Accounts][[Amount] == 100]

The following expression returns false if the Accounts collection is empty:

[Accounts][]

Refer to the following help topic for an example on how to use this syntax: How to Use an Aggregate Function in Calculated Fields.