Download as pdf or txt
Download as pdf or txt
You are on page 1of 98

Products

1853

Examples
W inForms Controls > Products > Pivot Grid > Examples
Examples
This section provides a list of examples, grouped by features, contained in this help. To get detailed information
on specific features, browse through the Concepts section.
Providing Data
How to: Bind a PivotGridControl to a Database
How to: Bind a PivotGridControl to an OLAP Cube Using the OLE DB Data Provider
How to: Bind a PivotGridControl to an OLAP Cube Using the ADOMD.NET Data Provider
How to: Bind a PivotGridControl to an OLAP Cube via XMLA
How to: Add an Unbound Field to Supply Additional Data
How to: Add an Unbound Field to Change Axis Detailing
How to: Provide Data for an Unbound Field Using Expressions
How to: Save PivotGridControl Data to a File and W ork with It Later
Data-Related Features
How to: Implement Custom Summary
How to: Display Underlying Records
How to: Add Custom Totals
How to: Calculate Multiple Custom Totals w ith Custom Summary Type
How to: Group Date-Time Values
How to: Implement Custom Group Intervals
How to: Implement the Sort by Summary Feature
How to: Sort Data by Columns (Rows) in Code
How to: Sort Data by Columns (Rows) in OLAP Mode
How to: Apply Filter to a Field
How to: Apply Summary Filter
How to: Prevent End-Users From Changing Filter Conditions
How to: Add and Remove Items From Filter Drop-Down Lists
How to: Implement Group Filter for a PivotGrid
How to: Change the Prefilter Criteria in Code
How to: Sort Filter Drop-Down Items in a Custom Manner
How to: Locate a Column (Row ) Header By Its Column's (Row's) Summary Values
Data Editing
How to: Assign an In-place Editor to a Data Field's Cells
How to: Assign In-place Editors to Particular Cells
How to: Prevent Editors from Being Opened for Individual Cells
Layout Features
How to: Group Fields
How to: Create User Folders w ithin the Customization Form
How to: Split Field Value Cells
How to: Hide Individual Rows and Columns
Data Formatting
How to: Format Cell Values
2013 DevExpress Inc.

1853

Products

1854

Data Output
How to: Visualize Pivot Grid Data via the XtraCharts Suite
How to: Customize PivotGridControl Data before Displaying It in a Chart Control
How to: Export Data
How to: Print a PivotGrid and Show its Print Preview
How to: Copy Data to the Clipboard
Appearance
How to: Customize Appearances of Cells via an Event
How to: Apply Conditional Formatting to Data Cells
How to: Custom Paint Cells
Miscellaneous
How to: Save and Restore Layout
How to: Save and Load Field Values' Collapsed States Together W ith Pivot Grid Layout
How to: Localize DevExpress Controls by Changing Default Resources
How to: Replace Default Resources with Their Equivalents
How to: Implement a Custom Serializer
Knowledge Base Articles
More examples and articles on this product can be found on our website. To browse through them, click on the
following link to go to the Online Know ledge Base:
Knowledge Base Articles

2013 DevExpress Inc.

1854

Products

1855

Providing Data
W inForms Controls > Products > Pivot Grid > Examples > Providing Data
This section contains the follow ing examples:
How to: Bind a PivotGridControl to a Database
How to: Bind a PivotGridControl to an OLAP Cube Using the OLE DB Data Provider
How to: Bind a PivotGridControl to an OLAP Cube Using the ADOMD.NET Data Provider
How to: Bind a PivotGridControl to an OLAP Cube via XMLA
How to: Add an Unbound Field to Supply Additional Data
How to: Add an Unbound Field to Change Axis Detailing
How to: Provide Data for an Unbound Field Using Expressions
How to: Save PivotGridControl Data to a File and W ork with It Later

2013 DevExpress Inc.

1855

Products

1856

How to: Bind a PivotGridControl to a Database


W inForms Controls > Products > Pivot Grid > Examples > Providing Data > How to: Bind a PivotGridControl to a
Database
The follow ing example demonstrates how to bind the XtraPivotGrid control to a View in the NWind.mdb database
that is shipped with the installation. The control will be used to analyze sales per countries, customers, product
categories and years.
Firstly, data is obtained from an MDB database via the OleDbConnection, OleDbDataAdapter and DataSet
components. The Data Binding Mechanism in ADO.NET document provides details on the process of connecting to
a database.
Secondly, the XtraPivotGrid control is bound to a table in the dataset via the PivotGridControl.DataSource
property.
Then PivotGridControl fields are created that w ill represent datasource fields. They are positioned w ithin
appropriate areas to analyze the data in the w ay w e w ant.
The result of the code is shown below:

C#

C opy C ode

using DevExpress.LookAndFeel;
using DevExpress.XtraPivotGrid;
using System.Data.OleDb;
// Create a connection object.
OleDbConnection connection =
new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\DB\\NWIND.MDB");
// Create a data adapter.
OleDbDataAdapter adapter = new OleDbDataAdapter("SELECT * FROM SalesPerson", connection);
// Create and fill a dataset.
DataSet sourceDataSet = new DataSet();
adapter.Fill(sourceDataSet, "SalesPerson");
// Assign the data source to the XtraPivotGrid control.
pivotGridControl1.DataSource = sourceDataSet.Tables["SalesPerson"];
// Create a row PivotGridControl field bound to the Country datasource field.
PivotGridField fieldCountry = new PivotGridField("Country", PivotArea.RowArea);
// Create a row PivotGridControl field bound to the Sales Person datasource field.
PivotGridField fieldCustomer = new PivotGridField("Sales Person", PivotArea.RowArea);
fieldCustomer.Caption = "Customer";
// Create a column PivotGridControl field bound to the OrderDate datasource field.
PivotGridField fieldYear = new PivotGridField("OrderDate", PivotArea.ColumnArea);
2013 DevExpress Inc.

1856

Products

1857

fieldYear.Caption = "Year";
// Group field values by years.
fieldYear.GroupInterval = PivotGroupInterval.DateYear;
// Create a column PivotGridControl field bound to the CategoryName datasource field.
PivotGridField fieldCategoryName = new PivotGridField("CategoryName", PivotArea.ColumnArea);
fieldCategoryName.Caption = "Product Category";
// Create a filter PivotGridControl field bound to the ProductName datasource field.
PivotGridField fieldProductName = new PivotGridField("ProductName", PivotArea.FilterArea);
fieldProductName.Caption = "Product Name";
// Create a data PivotGridControl field bound to the 'Extended Price' datasource field.
PivotGridField fieldExtendedPrice = new PivotGridField("Extended Price", PivotArea.DataArea);
fieldExtendedPrice.CellFormat.FormatType = DevExpress.Utils.FormatType.Numeric;
// Specify the formatting setting to format summary values as integer currency amount.
fieldExtendedPrice.CellFormat.FormatString = "c0";
// Add the fields to the control's field collection.
pivotGridControl1.Fields.AddRange(new PivotGridField[] {fieldCountry, fieldCustomer,
fieldCategoryName, fieldProductName, fieldYear, fieldExtendedPrice});
// Arrange the row fields within the Row Header Area.
fieldCountry.AreaIndex = 0;
fieldCustomer.AreaIndex = 1;
// Arrange the column fields within the Column Header Area.
fieldCategoryName.AreaIndex = 0;
fieldYear.AreaIndex = 1;
// Customize the control's look-and-feel via the Default LookAndFeel object.
UserLookAndFeel.Default.UseWindowsXPTheme = false;
UserLookAndFeel.Default.Style = LookAndFeelStyle.Skin;
UserLookAndFeel.Default.SkinName = "Money Twins";
Visual Basic

C opy C ode

Imports DevExpress.LookAndFeel
Imports DevExpress.XtraPivotGrid
Imports System.Data.OleDb
' Create a connection object.
Dim connection As OleDbConnection =
New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\DB\\NWIND.MDB")
' Create a data adapter.
Dim adapter As OleDbDataAdapter = New OleDbDataAdapter("SELECT * FROM SalesPerson", connection)
' Create and fill a dataset.
Dim sourceDataSet As DataSet = New DataSet
adapter.Fill(sourceDataSet, "SalesPerson")
' Assign the data source to the XtraPivotGrid control.
PivotGridControl1.DataSource = sourceDataSet.Tables("SalesPerson")
' Create a row PivotGridControl field bound to the Country datasource field.
Dim fieldCountry As PivotGridField = New PivotGridField("Country", PivotArea.RowArea)
' Create a row PivotGridControl field bound to the Sales Person datasource field.
Dim fieldCustomer As PivotGridField = New PivotGridField("Sales Person", PivotArea.RowArea)
fieldCustomer.Caption = "Customer"
' Create a column PivotGridControl field bound to the OrderDate datasource field.
Dim fieldYear As PivotGridField = New PivotGridField("OrderDate", PivotArea.ColumnArea)
fieldYear.Caption = "Year"
' Group field values by years.
fieldYear.GroupInterval = PivotGroupInterval.DateYear
' Create a column PivotGridControl field bound to the CategoryName datasource field.
Dim fieldCategoryName As PivotGridField = New PivotGridField("CategoryName", PivotArea.ColumnArea)
fieldCategoryName.Caption = "Product Category"
' Create a filter PivotGridControl field bound to the ProductName datasource field.
Dim fieldProductName As PivotGridField = New PivotGridField("ProductName", PivotArea.FilterArea)
fieldProductName.Caption = "Product Name"
' Create a data PivotGridControl field bound to the 'Extended Price' datasource field.
Dim fieldExtendedPrice As PivotGridField = New PivotGridField("Extended Price", PivotArea.DataArea)
fieldExtendedPrice.CellFormat.FormatType = DevExpress.Utils.FormatType.Numeric
2013 DevExpress Inc.

1857

Products

1858

' Specify the formatting setting to format summary values as integer currency amount.
fieldExtendedPrice.CellFormat.FormatString = "c0"
' Add the fields to the control's field collection.
PivotGridControl1.Fields.AddRange(New PivotGridField() {fieldCountry, fieldCustomer, _
fieldCategoryName, fieldProductName, fieldYear, fieldExtendedPrice})
' Arrange the row fields within the Row Header Area.
fieldCountry.AreaIndex = 0
fieldCustomer.AreaIndex = 1
' Arrange the column fields within the Column Header Area.
fieldCategoryName.AreaIndex = 0
fieldYear.AreaIndex = 1
' Customize the control's look-and-feel via the Default LookAndFeel object.
UserLookAndFeel.Default.UseWindowsXPTheme = False
UserLookAndFeel.Default.Style = LookAndFeelStyle.Skin
UserLookAndFeel.Default.SkinName = "Money Twins"

2013 DevExpress Inc.

1858

Products

1859

How to: Bind a PivotGridControl to an OLAP Cube Using the OLE DB Data Pro
W inForms Controls > Products > Pivot Grid > Examples > Providing Data > How to: Bind a PivotGridControl to an
OLAP Cube Using the OLE DB Data Provider
The follow ing example shows how to view data from an OLAP server (MS SQL Server 2005 Analysis Services) in
the PivotGridControl.
Prerequisites
In the example, the PivotGridControl is bound to an Adventure Works cube in MS SQL Server 2005 Analysis
Services (SSAS). It's assumed that you have the standard AdventureW orksDW (data w arehouse) database
installed and the Adventure W orks cube deployed to your instance of MS SQL Server 2005. By default, this
database and the cube are not installed.
To install the AdventureWorksDW database, use MS SQL Server 2005 setup, as described in the following topic:
Running Setup to Install AdventureWorks Sample Databases and Samples.
To deploy the Adventure W orks cube to your instance of SSAS, please do the follow ing:
1.In Visual Studio 2005, open the Enterprise version of the "AdventureWorks Analysis Services
Project" (this project is installed along w ith the AdventureWorksDW database, by default, to the
directory:

C:\Program Files\Microsoft SQL Server\90\Tools\Samples\AdventureWorks Analysis


Services Project\Enterprise
2.Deploy the cubes that are defined in the project by selecting Build->Deploy menu option. The Adventure
Works cube will be deployed to the local instance of SSAS.
Now it's possible to view this cube within the PivotGridControl. See the following section for step-by-step
instructions.
Displaying Data in PivotGridControl - Design-Time Example
The steps below show how to view data from the Adventure W orks cube in the PivotGridControl.
1.Create a new W indows Application project in Visual Studio.
2.Drop the PivotGridControl onto the form and select it in the Properties window .
3.In the Properties window , focus the PivotGridControl.OLAPConnectionString property and click the
ellipsis (...) button. This w ill invoke the Connection String Editor.
4.In the editor, specify the connection settings to the cube. First, specify the server name that runs the
required instance of SSAS (type "localhost" if the local MS SQL Server 2005 is used). Then click the
dropdow n button in the Catalog edit box. This should list the names of all data catalogs that exist on
the specified instance of SSAS. Select the "Adventure Works DW" item.
Click the dropdown button in the Cube edit box to open the list of available cubes in the specified
catalog. Select the "Adventure W orks" cube:

Click the OK button to submit the connection settings.


5.Run the PivotGridControl's Designer by right-clicking on the control and selecting the Run Designer
option. The Fields page will be opened.
6.Ensure that the Field List pane that displays all available fields in the bound cube is visible. If the pane
is hidden, click the ">>" (Show Field List) button at the top of the designer.
7.Locate the "[Measures].[Internet Sales Amount]" field in the Field List pane. This field will be
represented by a Data Field in the PivotGridControl.
To create a PivotGridField object for this field, drag the "[Measures].[Internet Sales Amount]" item onto
2013 DevExpress Inc.

1859

Products

1860
the PivotGrid Fields pane (or simply double-click it w ithin the Field List pane).
To position the created field within the Data Header Area, set the field's PivotGridFieldBase.Area
property to the PivotArea.DataArea value in the Properties grid.

8.Locate the "[Customer].[Country].[Country]" field in the Field List pane. This field will be represented by
a Row Field in the PivotGridControl.
Drag this field onto the PivotGrid Fields list and set the created PivotGridField's PivotGridFieldBase.Area
property to the PivotArea.RowArea value.
9.Locate the "[Date].[Fiscal Year].[Fiscal Year]" field in the Field List pane. This field will be represented
by a Column Field in the PivotGridControl.
Drag this field onto the PivotGrid Fields list. The created PivotGridField's PivotGridFieldBase.Area
property will be already set to the PivotArea.ColumnArea value. Leave this value unchanged.
10.Close the designer. The PivotGridControl will display three fields in the Data, Column and Row areas
respectively.

11.Run the project. The form w ill look like the image below, showing data retrieved from the Adventure
Works cube.

2013 DevExpress Inc.

1860

Products

1861

Displaying Data in PivotGridControl - Runtime Example


The follow ing code shows how to view data from the Adventure Works cube at runtime. It's equivalent to the
design-time steps from the previous section.
C#

C opy C ode

using DevExpress.XtraPivotGrid;
// Create a PivotGridControl.
PivotGridControl pivotControl = new PivotGridControl();
pivotControl.Dock = DockStyle.Fill;
this.Controls.Add(pivotControl);
// Specify the connection string
pivotControl.OLAPConnectionString = "Provider=msolap;Data Source=localhost;Initial Catalog=Adventure Wo
// Create fields.
PivotGridField fieldMeasuresInternetSalesAmount = new PivotGridField("[Measures].[Internet Sales Amount
fieldMeasuresInternetSalesAmount.Caption = "Internet Sales Amount";
PivotGridField fieldCustomerCountryCountry = new PivotGridField("[Customer].[Country].[Country]", PivotA
fieldCustomerCountryCountry.Caption = "Country";
PivotGridField fieldDateFiscalYearFiscalYear = new PivotGridField("[Date].[Fiscal Year].[Fiscal Year]",
fieldDateFiscalYearFiscalYear.Caption = "Fiscal Year";
// Add fields to the PivotGridControl
pivotControl.Fields.AddRange(new PivotGridField[] { fieldMeasuresInternetSalesAmount, fieldCustomerCoun
fieldDateFiscalYearFiscalYear });
Visual Basic

C opy C ode

Imports DevExpress.XtraPivotGrid
' Create a PivotGridControl.
Dim pivotControl As PivotGridControl = New PivotGridControl()
pivotControl.Dock = DockStyle.Fill
Me.Controls.Add(pivotControl)
' Specify the connection string
pivotControl.OLAPConnectionString = "Provider=msolap;Data Source=localhost;Initial Catalog=Adventure Wo
' Create fields.
Dim fieldMeasuresInternetSalesAmount As PivotGridField = New PivotGridField("[Measures].[Internet Sales
fieldMeasuresInternetSalesAmount.Caption = "Internet Sales Amount"
Dim fieldCustomerCountryCountry As PivotGridField = New PivotGridField("[Customer].[Country].[Country]"
fieldCustomerCountryCountry.Caption = "Country"
Dim fieldDateFiscalYearFiscalYear As PivotGridField = New PivotGridField("[Date].[Fiscal Year].[Fiscal
fieldDateFiscalYearFiscalYear.Caption = "Fiscal Year"
' Add fields to the PivotGridControl
pivotControl.Fields.AddRange(New PivotGridField() {fieldMeasuresInternetSalesAmount, fieldCustomerCount
fieldDateFiscalYearFiscalYear})

2013 DevExpress Inc.

1861

Products

1862

How to: Bind a PivotGridControl to an OLAP Cube Using the ADOMD.NET Data
W inForms Controls > Products > Pivot Grid > Examples > Providing Data > How to: Bind a PivotGridControl to an
OLAP Cube Using the ADOMD.NET Data Provider
Show Me
The complete sample project is available in the DevExpress Code Central database at http://w ww .devexpress.com/
example=E3705. Depending on the target platform type (ASP.NET, W inForms, etc), you can either run this example
online or dow nload an auto-executable sample.
The follow ing example demonstrates how to bind a PivotGridControl to an OLAP cube via the ADOMD.NET data
provider.
In this example, the PivotGridControl.OLAPDataProvider property is used to specify that the PivotGridControl
should use the ADOMD.NET data provider to access an OLAP cube. OLAP connection parameters are specified in a
connection string passed to the PivotGridControl.OLAPConnectionString property. The follow ing parameters are
provided:
Data Source - a path to a local cube file that w ill serve as a datasource.
Initial Catalog - a data catalog that contains cubes.
Cube Name - the name of the cube that provides OLAP data.
C#

C opy C ode

(Form1.cs)
using System;
using System.Windows.Forms;
using DevExpress.XtraPivotGrid;
namespace XtraPivotGrid_ADOMD {
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
}
void Form1_Load(object sender, EventArgs e) {
// Specifies that PivotGridControl should use the ADOMD.NET data provider
// to bind to an OLAP cube.
pivotGridControl1.OLAPDataProvider = OLAPDataProvider.Adomd;
// Configures a data connection.
// Specifies a string that encapsulates connection parameters
// required to access the desired OLAP cube.
pivotGridControl1.OLAPConnectionString =
"Data Source=http://demos.devexpress.com/Services/OLAP/msmdpump.dll;" +
"Initial Catalog=Adventure Works DW Standard Edition;Cube Name=Adventure Works;";
}
}
}
Visual Basic

C opy C ode

(Form1.vb)
Imports Microsoft.VisualBasic
Imports System
Imports System.Windows.Forms
Imports DevExpress.XtraPivotGrid
Namespace XtraPivotGrid_ADOMD
Partial Public Class Form1
Inherits Form
Public Sub New()
InitializeComponent()
End Sub
Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.Load
' Specifies that PivotGridControl should use the ADOMD.NET data provider
' to bind to an OLAP cube.
pivotGridControl1.OLAPDataProvider = OLAPDataProvider.Adomd

2013 DevExpress Inc.

1862

Products

1863

' Configures a data connection.


' Specifies a string that encapsulates connection parameters
' required to access the desired OLAP cube.
pivotGridControl1.OLAPConnectionString = _
"Data Source=http://demos.devexpress.com/Services/OLAP/msmdpump.dll;" & _
"Initial Catalog=Adventure Works DW Standard Edition;Cube Name=Adventure Works;"
End Sub
End Class
End Namespace

2013 DevExpress Inc.

1863

Products

1864

How to: Bind a PivotGridControl to an OLAP Cube via XMLA


W inForms Controls > Products > Pivot Grid > Examples > Providing Data > How to: Bind a PivotGridControl to an
OLAP Cube via XMLA
Show Me
The complete sample project is available in the DevExpress Code Central database at http://w ww .devexpress.com/
example=E3708. Depending on the target platform type (ASP.NET, W inForms, etc), you can either run this example
online or dow nload an auto-executable sample.
The follow ing example demonstrates how to bind a PivotGridControl to an OLAP cube via the XMLA data access
standard.
In this example, the PivotGridControl.OLAPDataProvider property is used to specify that the PivotGridControl
should use the XMLA data access standard to bind to an OLAP cube. OLAP connection parameters are specified in
a connection string passed to the PivotGridControl.OLAPConnectionString property. The following parameters are
provided:
Data Source - a path to a data pump.
Initial Catalog - a data catalog that contains cubes.
Cube Name - the name of the cube that provides OLAP data.
C#

C opy C ode

(Form1.cs)
using System;
using System.Windows.Forms;
using DevExpress.XtraPivotGrid;
namespace XtraPivotGrid_XMLA {
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
}
void Form1_Load(object sender, EventArgs e) {
// Specifies that PivotGridControl should use the XMLA data access standard
// to bind to an OLAP cube.
pivotGridControl1.OLAPDataProvider = OLAPDataProvider.Xmla;
// Configures a data connection.
// Specifies a string that encapsulates connection parameters
// required to access the desired OLAP cube.
pivotGridControl1.OLAPConnectionString =
"Data Source=http://demos.devexpress.com/Services/OLAP/msmdpump.dll;" +
"Initial Catalog=Adventure Works DW Standard Edition;Cube Name=Adventure Works";
}
}
}
Visual Basic

C opy C ode

(Form1.vb)
Imports Microsoft.VisualBasic
Imports System
Imports System.Windows.Forms
Imports DevExpress.XtraPivotGrid
Namespace XtraPivotGrid_XMLA
Partial Public Class Form1
Inherits Form
Public Sub New()
InitializeComponent()
End Sub
Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.Load
' Specifies that PivotGridControl should use the XMLA data access standard
' to bind to an OLAP cube.
pivotGridControl1.OLAPDataProvider = OLAPDataProvider.Xmla

2013 DevExpress Inc.

1864

Products

1865

' Configures a data connection.


' Specifies a string that encapsulates connection parameters
' required to access the desired OLAP cube.
pivotGridControl1.OLAPConnectionString = _
"Data Source=http://demos.devexpress.com/Services/OLAP/msmdpump.dll;" & _
"Initial Catalog=Adventure Works DW Standard Edition;Cube Name=Adventure Works"
End Sub
End Class
End Namespace

2013 DevExpress Inc.

1865

Products

1866

How to: Add an Unbound Field to Supply Additional Data


W inForms Controls > Products > Pivot Grid > Examples > Providing Data > How to: Add an Unbound Field to
Supply Additional Data
Assume that the XtraPivotGrid control is bound to an "Order Details" data table (NW ind data base) which contains
"UnitPrice", "Quantity" and "Discount" fields. There isn't any field w hich represents the total sum, however this
can be calculated manually as follows: UnitPrice*Quantity*(1-Discount). This example show s how to add an
unbound field to the XtraPivotGrid control, in this case to represent the total sum of an order.
Firstly, a field w ith a unique field name ("Total Sum") is created. An unbound field's PivotGridFieldBase.FieldName
property must be unique and different than those in the control's data source.
Secondly, the field's PivotGridFieldBase.UnboundType property is set to UnboundColumnType.Decimal since the
field is supposed to display floating values.
Finally, the PivotGridControl.CustomUnboundFieldData event is handled to populate the field with data.

C#

C opy C ode

using DevExpress.XtraPivotGrid;
// Create a field with the specified field name.
PivotGridField unboundField = pivotGridControl1.Fields.Add("Total Sum",
PivotArea.DataArea);
// Specify the type of the field's values.
unboundField.UnboundType = DevExpress.Data.UnboundColumnType.Decimal;
// Populates the unbound field.
private void pivotGridControl1_CustomUnboundFieldData(object sender,
CustomFieldDataEventArgs e) {
if(e.Field.FieldName == "Total Sum") {
decimal unitPrice = Convert.ToDecimal(e.GetListSourceColumnValue("UnitPrice"));
int qty = Convert.ToInt32(e.GetListSourceColumnValue("Quantity"));
decimal discount = Convert.ToDecimal(e.GetListSourceColumnValue("Discount"));
e.Value = unitPrice*qty*(1-discount);
}
}
Visual Basic

C opy C ode

Imports DevExpress.XtraPivotGrid
' Create a field with the specified field name.
Dim unboundField As PivotGridField = pivotGridControl1.Fields.Add("Total Sum",
PivotArea.DataArea)
' Specify the type of the field's values.
unboundField.UnboundType = DevExpress.Data.UnboundColumnType.Decimal
' Populates the unbound field.
Private Sub pivotGridControl1_CustomUnboundFieldData(ByVal sender As System.Object, _
ByVal e As CustomFieldDataEventArgs)
If (e.Field.FieldName = "Total Sum") Then
2013 DevExpress Inc.

1866

Products

1867

Dim unitPrice As Decimal = Convert.ToDecimal(e.GetListSourceColumnValue("UnitPrice"))


Dim qty As Int32 = Convert.ToInt32(e.GetListSourceColumnValue("Quantity"))
Dim discount As Decimal = Convert.ToDecimal(e.GetListSourceColumnValue("Discount"))
e.Value = unitPrice * qty * (1 - discount)
End If
End Sub

2013 DevExpress Inc.

1867

Products

1868

How to: Add an Unbound Field to Change Axis Detailing


W inForms Controls > Products > Pivot Grid > Examples > Providing Data > How to: Add an Unbound Field to
Change Axis Detailing
This example show s how custom group intervals can be implemented.
The image below show s a sample report w hich displays the average salary and seniority of employees.
Employees are grouped by their age and department.

To compact the report further and make it more readable, the values in the Age axis are grouped. This axis will
show two intervals ("Under 30" and "Over 30") rather than display each unique age. To do this the following
steps are performed:
an unbound field is created;
the PivotGridControl.CustomUnboundFieldData event is handled to supply group values to the unbound
field;
the PivotGridControl.FieldValueDisplayText event is handled to substitute group values with user-friendly
text.
The image below show s the result:

C#

C opy C ode

private void pivotGridControl1_CustomUnboundFieldData(object sender, DevExpress.XtraPivotGrid.CustomFie


if(e.Field != fieldAgeRange) return;
if((int)e.GetListSourceColumnValue("Age") > 30) e.Value = 1;
else e.Value = 0;
}

2013 DevExpress Inc.

1868

Products

1869

private void pivotGridControl1_FieldValueDisplayText(object sender, DevExpress.XtraPivotGrid.PivotField


if(e.Field == null) return;
if(e.Field != fieldAgeRange) return;
e.DisplayText = ((int)e.Value == 1) ? "Over 30" : "Under 30";
}
Visual Basic

C opy C ode

Private Sub pivotGridControl1_CustomUnboundFieldData(ByVal sender As Object, _


ByVal e As DevExpress.XtraPivotGrid.CustomFieldDataEventArgs) Handles pivotGridControl1.CustomUnbou
If Not (e.Field Is fieldAgeRange) Then Return
If CInt(e.GetListSourceColumnValue("Age")) > 30 Then
e.Value = 1
Else
e.Value = 0
End If
End Sub
Private Sub pivotGridControl1_FieldValueDisplayText(ByVal sender As Object, _
ByVal e As DevExpress.XtraPivotGrid.PivotFieldDisplayTextEventArgs) Handles pivotGridControl1.FieldV
If e.Field Is Nothing Then
Exit Sub
End If
If Not (e.Field Is fieldAgeRange) Then Return
If CInt(e.Value) = 1 Then
e.DisplayText = "Over 30"
Else
e.DisplayText = "Under 30"
End If
End Sub

2013 DevExpress Inc.

1869

Products

1870

How to: Provide Data for an Unbound Field Using Expressions


W inForms Controls > Products > Pivot Grid > Examples > Providing Data > How to: Provide Data for an Unbound
Field Using Expressions
The follow ing example shows how to create an unbound field using expressions. An Extended Price field is
created, w hose values are calculated according to the expression: [Quantity] * [UnitPrice] * (1 - [Discount]).
Note that when the PivotGridOptionsData.DataFieldUnboundExpressionMode property is set to
UseSummaryValues, the PivotGridFieldBase.FieldName and PivotGridFieldBase.Name properties cannot be used
in unbound expressions to refer to fields. Use the PivotGridFieldBase.ExpressionFieldName property instead.
C#

C opy C ode

PivotGridField fieldExtPrice = new PivotGridField("fieldExtPrice", PivotArea.DataArea);


fieldExtPrice.Caption = "Ext Price";
fieldExtPrice.UnboundType = DevExpress.Data.UnboundColumnType.Decimal;
fieldExtPrice.UnboundExpression = "[" + fieldQuantity.ExpressionFieldName + "] * [" +
fieldUnitPrice.ExpressionFieldName + "] * (1 - [" +
fieldDiscount.ExpressionFieldName + "])";
pivotGridControl1.Fields.Add(fieldExtPrice);
Visual Basic

C opy C ode

Dim fieldExtPrice As PivotGridField = New PivotGridField("fieldExtPrice", PivotArea.DataArea)


fieldExtPrice.Caption = "Ext Price"
fieldExtPrice.UnboundType = DevExpress.Data.UnboundColumnType.Decimal
fieldExtPrice.UnboundExpression = "[" + fieldQuantity.ExpressionFieldName + "] * [" + _
fieldUnitPrice.ExpressionFieldName + "] * (1 - [" + _
fieldDiscount.ExpressionFieldName + "])"
PivotGridControl1.Fields.Add(fieldExtPrice)

2013 DevExpress Inc.

1870

Products

1871

How to: Save PivotGridControl Data to a File and Work with It Later
W inForms Controls > Products > Pivot Grid > Examples > Providing Data > How to: Save PivotGridControl Data to
a File and Work with It Later
The follow ing example shows how to save the PivotGridControl's data to a file, and then load it later.
To save the data the PivotGridControl.SavePivotGridToFile method is called. To restore the data, a
PivotFileDataSource object is initialized and assigned to the PivotGridControl.DataSource property.
C#

C opy C ode

using DevExpress.Data.PivotGrid;
string filePath = "c:\\pivotData.dat";
// Save the control's data to the file.
pivotGridControl1.SavePivotGridToFile(filePath);
//...
// Restore the saved data
PivotFileDataSource ds = new PivotFileDataSource(filePath);
pivotGridControl1.DataSource = ds;
Visual Basic

C opy C ode

Imports DevExpress.Data.PivotGrid
Dim filePath As String = "c:\\pivotData.dat"
' Save the control's data to the file.
pivotGridControl1.SavePivotGridToFile(filePath)
'...
' Restore the saved data
Dim ds As PivotFileDataSource = New PivotFileDataSource(filePath)
pivotGridControl1.DataSource = ds

2013 DevExpress Inc.

1871

Products

1872

Data-Related Features
W inForms Controls > Products > Pivot Grid > Examples > Data-Related Features
This section contains the follow ing examples:
How to: Implement Custom Summary
How to: Display Underlying Records
How to: Add Custom Totals
How to: Calculate Multiple Custom Totals w ith Custom Summary Type
How to: Group Date-Time Values
How to: Implement Custom Group Intervals
How to: Implement the Sort by Summary Feature
How to: Sort Data by Columns (Rows) in Code
How to: Sort Data by Columns (Rows) in OLAP Mode
How to: Apply Filter to a Field
How to: Apply Summary Filter
How to: Prevent End-Users From Changing Filter Conditions
How to: Add and Remove Items From Filter Drop-Down Lists
How to: Implement Group Filter for a PivotGrid
How to: Change the Prefilter Criteria in Code
How to: Use Asynchronous Operations That Return the Result
How to: Sort Filter Drop-Down Items in a Custom Manner
How to: Locate a Column (Row ) Header By Its Column's (Row's) Summary Values

2013 DevExpress Inc.

1872

Products

1873

How to: Implement Custom Summary


W inForms Controls > Products > Pivot Grid > Examples > Data-Related Features > How to: Implement Custom
Summary
The follow ing example shows how to calculate a custom summary.
Assume that the XtraPivotGrid control is bound to an "Orders" table which contains order information (order id,
product name, extended price, etc). A field which displays the ratio of orders over $500 is to be added.
In this example the custom summary is calculated against the "Extended Price" field. It's
PivotGridCustomTotalBase.SummaryType property is set to PivotSummaryType.Custom and the caption to
"Percentage of Orders over $500". The PivotGridControl.CustomSummary event is handled to only count those
records whose total sum exceeds
. The ratio of these records to all the records is a custom summary value
and therefore is assigned to the PivotGridCustomSummaryEventArgsBase<T>.CustomValue parameter.
The follow ing image shows the result of the custom summary calculation:

C#

C opy C ode

using DevExpress.XtraPivotGrid;
fieldExtendedPrice.Caption = "Percentage of Orders over $500";
// Enable a custom summary calculation for the Extended Price field.
fieldExtendedPrice.SummaryType = DevExpress.Data.PivotGrid.PivotSummaryType.Custom;
// Specify the settings used to format values.
fieldExtendedPrice.CellFormat.FormatType = DevExpress.Utils.FormatType.Numeric;
fieldExtendedPrice.CellFormat.FormatString = "p";
int minSum = 500;
private void pivotGridControl1_CustomSummary(object sender,
PivotGridCustomSummaryEventArgs e) {
if(e.DataField != fieldExtendedPrice) return;
// A variable which counts the number of orders whose sum exceeds $500.
int order500Count = 0;
// Get the record set corresponding to the current cell.
PivotDrillDownDataSource ds = e.CreateDrillDownDataSource();
// Iterate through the records and count the orders.
for(int i = 0; i < ds.RowCount; i++) {
PivotDrillDownDataRow row = ds[i];
// Get the order's total sum.
decimal orderSum = (decimal)row[fieldExtendedPrice];
if(orderSum >= minSum) order500Count ++;
}
// Calculate the percentage.
if(ds.RowCount > 0) {
e.CustomValue = (decimal)order500Count/ds.RowCount;
}
}

2013 DevExpress Inc.

1873

Products
Visual Basic

1874
C opy C ode

Imports DevExpress.XtraPivotGrid
fieldExtendedPrice.Caption = "Percentage of Orders over $500"
' Enable a custom summary calculation for the Extended Price field.
fieldExtendedPrice.SummaryType = DevExpress.Data.PivotGrid.PivotSummaryType.Custom
' Specify the settings used to format values.
fieldExtendedPrice.CellFormat.FormatType = DevExpress.Utils.FormatType.Numeric
fieldExtendedPrice.CellFormat.FormatString = "p"
Dim minSum As Integer = 500
Private Sub PivotGridControl1_CustomSummary(ByVal sender As Object, _
ByVal e As PivotGridCustomSummaryEventArgs) Handles PivotGridControl1.CustomSummary
If Not e.DataField Is fieldExtendedPrice Then Return
' A variable which counts the number of orders whose sum exceeds $500.
Dim order500Count As Integer = 0
' Get the record set corresponding to the current cell.
Dim ds As PivotDrillDownDataSource = e.CreateDrillDownDataSource()
' Iterate through the records and count the orders.
Dim i As Integer
For i = 0 To ds.RowCount - 1
Dim row As PivotDrillDownDataRow = ds(i)
' Get the order's total sum.
Dim orderSum As Decimal = row(fieldExtendedPrice)
If orderSum >= minSum Then order500Count = order500Count + 1
Next
' Calculate the percentage.
If ds.RowCount > 0 Then
e.CustomValue = order500Count / ds.RowCount
End If
End Sub

2013 DevExpress Inc.

1874

Products

1875

How to: Display Underlying Records


W inForms Controls > Products > Pivot Grid > Examples > Data-Related Features > How to: Display Underlying
Records
The follow ing example shows how to display the records from the control's underlying data source which
correspond to a particular cell. A new form that displays these records is opened w hen a particular cell in the
XtraPivotGrid control is double-clicked.
In the example the PivotGridControl.CellDoubleClick event is handled. The PivotCellBaseEventArgs.
CreateDrillDow nDataSource method is called to obtain the list of records associated with the clicked cell.
The follow ing image shows a sample PivotGridControl w hich is bound to the Invoices table in the nw ind.mdb
database:

Clicking the third cell in the 1994 column w ill invoke the following form:

It lists all the orders made in 1994 by Belgian customers.


C#

C opy C ode

using DevExpress.XtraPivotGrid;
private void pivotGridControl1_CellDoubleClick(object sender, PivotCellEventArgs e) {
// Create a new form.
Form form = new Form();
form.Text = "Records";
// Place a DataGrid control on the form.
DataGrid grid = new DataGrid();
grid.Parent = form;
grid.Dock = DockStyle.Fill;
// Get the recrd set associated with the current cell and bind it to the grid.
grid.DataSource = e.CreateDrillDownDataSource();
form.Bounds = new Rectangle(100, 100, 500, 400);
// Display the form.
form.ShowDialog();
form.Dispose();
}

2013 DevExpress Inc.

1875

Products
Visual Basic

1876
C opy C ode

Imports DevExpress.XtraPivotGrid
Private Sub pivotGridControl1_CellDoubleClick(ByVal sender As Object, _
ByVal e As PivotCellEventArgs) Handles pivotGridControl1.CellDoubleClick
' Create a new form.
Dim form As Form = New Form
form.Text = "Records"
' Place a DataGrid control on the form.
Dim grid As DataGrid = New DataGrid
grid.Parent = form
grid.Dock = DockStyle.Fill
' Get the recrd set associated with the current cell and bind it to the grid.
grid.DataSource = e.CreateDrillDownDataSource()
form.Bounds = New Rectangle(100, 100, 500, 400)
' Display the form.
form.ShowDialog()
form.Dispose()
End Sub

2013 DevExpress Inc.

1876

Products

1877

How to: Add Custom Totals


W inForms Controls > Products > Pivot Grid > Examples > Data-Related Features > How to: Add Custom Totals
In the following example, four custom totals are added for a 'Category Name' row field. They will calculate the
total Average, Sum, Min and Max values against the currently displayed data field.
The result is show n below :

C#

C opy C ode

using DevExpress.Data.PivotGrid;
using DevExpress.XtraPivotGrid;
// Get a reference to the CategoryName field.
PivotGridField field = pivotGridControl1.Fields["CategoryName"];
pivotGridControl1.BeginUpdate();
try {
// Clear the custom total collection.
field.CustomTotals.Clear();
// Add four items to the custom total collection to calculate the Average,
// Sum, Max and Min summaries.
field.CustomTotals.Add(PivotSummaryType.Average);
field.CustomTotals.Add(PivotSummaryType.Sum);
field.CustomTotals.Add(PivotSummaryType.Max);
field.CustomTotals.Add(PivotSummaryType.Min);
// Make the custom totals visible for this field.
field.TotalsVisibility = PivotTotalsVisibility.CustomTotals;
}
finally {
pivotGridControl1.EndUpdate();
}
Visual Basic

C opy C ode

Imports DevExpress.Data.PivotGrid
Imports DevExpress.XtraPivotGrid
' Get a reference to the CategoryName field.
Dim field As PivotGridField = pivotGridControl1.Fields("CategoryName")
pivotGridControl1.BeginUpdate()
Try
' Clear the custom total collection.
field.CustomTotals.Clear()
' Add four items to the custom total collection to calculate the Average,
' Sum, Max and Min summaries.

2013 DevExpress Inc.

1877

Products

1878

field.CustomTotals.Add(PivotSummaryType.Average)
field.CustomTotals.Add(PivotSummaryType.Sum)
field.CustomTotals.Add(PivotSummaryType.Max)
field.CustomTotals.Add(PivotSummaryType.Min)
' Make the custom totals visible for this field.
field.TotalsVisibility = PivotTotalsVisibility.CustomTotals
Finally
pivotGridControl1.EndUpdate()
End Try

2013 DevExpress Inc.

1878

Products

1879

How to: Calculate Multiple Custom Totals with Custom Summary Type
W inForms Controls > Products > Pivot Grid > Examples > Data-Related Features > How to: Calculate Multiple
Custom Totals with Custom Summary Type
Show Me
The complete sample project is available in the DevExpress Code Central database at http://w ww .devexpress.com/
example=E3815. Depending on the target platform type (ASP.NET, W inForms, etc), you can either run this example
online or dow nload an auto-executable sample.
The follow ing example demonstrates how to calculate and display multiple Custom Totals for a field.
In this example, tw o Custom Totals are implemented for the Category Name field. The first one displays a median
calculated against summary values, while the second one displays the first and third quartiles.
To accomplish this task, we create two PivotGridCustomTotal objects and set their summary type to
PivotSummaryType.Custom. W e also assign the Custom Totals' names to PivotGridCustomTotalBase.Tag
properties to be able to distinguish between the Custom Totals when w e calculate their values. Finally, we add
the created objects to the Category Name field's PivotGridField.CustomTotals collection and enable the Custom
Totals to be displayed for this field by setting the PivotGridFieldBase.TotalsVisibility property to PivotTotalsVisibility.
CustomTotals.
Custom Total values are actually calculated in the PivotGridControl.CustomCellValue event. First, the event
handler prepares a list of summary values against which a Custom Total will be calculated. For this purpose, it
creates a summary datasource and copies the summary values to an array. After that, the array is sorted and
passed to an appropriate method that calculates a median or quartile value against the provided array. Finally,
the resulting value is assigned to the event parameter's PivotCellValueEventArgs.Value property.
C#

C opy C ode

(Form1.cs)
using System;
using System.Collections;
using System.Windows.Forms;
using DevExpress.Data.PivotGrid;
using DevExpress.XtraPivotGrid;
namespace XtraPivotGrid_MultipleCustomTotals {
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e) {
// Binds the pivot grid to data.
nwindDataSetTableAdapters.ProductReportsTableAdapter adapter =
new nwindDataSetTableAdapters.ProductReportsTableAdapter();
pivotGridControl1.DataSource = adapter.GetData();
// Creates a PivotGridCustomTotal object that defines the Median Custom Total.
PivotGridCustomTotal medianCustomTotal = new PivotGridCustomTotal(PivotSummaryType.Custom);
// Specifies a unique PivotGridCustomTotal.Tag property value
// that will be used to distinguish between two Custom Totals.
medianCustomTotal.Tag = "Median";
// Specifies formatting settings that will be used to display
// Custom Total column/row headers.
medianCustomTotal.Format.FormatString = "{0} Median";
medianCustomTotal.Format.FormatType = DevExpress.Utils.FormatType.Custom;
// Adds the Median Custom Total for the Category Name field.
fieldCategoryName.CustomTotals.Add(medianCustomTotal);
// Creates a PivotGridCustomTotal object that defines the Quartiles Custom Total.
PivotGridCustomTotal quartileCustomTotal = new PivotGridCustomTotal(PivotSummaryType.Custom
// Specifies a unique PivotGridCustomTotal.Tag property value
// that will be used to distinguish between two Custom Totals.
quartileCustomTotal.Tag = "Quartiles";
// Specifies formatting settings that will be used to display
// Custom Total column/row headers.
quartileCustomTotal.Format.FormatString = "{0} Quartiles";

2013 DevExpress Inc.

1879

Products

1880
quartileCustomTotal.Format.FormatType = DevExpress.Utils.FormatType.Custom;
// Adds the Quartiles Custom Total for the Category Name field.
fieldCategoryName.CustomTotals.Add(quartileCustomTotal);
// Enables the Custom Totals to be displayed instead of Automatic Totals.
fieldCategoryName.TotalsVisibility = PivotTotalsVisibility.CustomTotals;
}
// Handles the CustomCellValue event.
// Fires for each data cell. If the processed cell is a Custom Total,
// provides an appropriate Custom Total value.
private void pivotGridControl1_CustomCellValue(object sender, PivotCellValueEventArgs e) {
// Exits if the processed cell does not belong to a Custom Total.
if (e.ColumnCustomTotal == null && e.RowCustomTotal == null) return;
// Obtains a list of summary values against which
// the Custom Total will be calculated.
ArrayList summaryValues = GetSummaryValues(e);
// Obtains the name of the Custom Total that should be calculated.
string customTotalName = GetCustomTotalName(e);
// Calculates the Custom Total value and assigns it to the Value event parameter.
e.Value = GetCustomTotalValue(summaryValues, customTotalName);
}
// Returns the Custom Total name.
private string GetCustomTotalName(PivotCellValueEventArgs e) {
return e.ColumnCustomTotal != null ?
e.ColumnCustomTotal.Tag.ToString() :
e.RowCustomTotal.Tag.ToString();
}
// Returns a list of summary values against which
// a Custom Total will be calculated.
private ArrayList GetSummaryValues(PivotCellValueEventArgs e) {
ArrayList values = new ArrayList();
// Creates a summary data source.
PivotSummaryDataSource sds = e.CreateSummaryDataSource();
// Iterates through summary data source records
// and copies summary values to an array.
for (int i = 0; i < sds.RowCount; i++) {
object value = sds.GetValue(i, e.DataField);
if (value == null) {
continue;
}
values.Add(value);
}
// Sorts summary values.
values.Sort();
// Returns the summary values array.
return values;
}
// Returns the Custom Total value by an array of summary values.
private object GetCustomTotalValue(ArrayList values, string customTotalName) {
// Returns a null value if the provided array is empty.
if (values.Count == 0) {
return null;
}
// If the Median Custom Total should be calculated,
// calls the GetMedian method.
if (customTotalName == "Median") {
return GetMedian(values);
}
// If the Quartiles Custom Total should be calculated,
// calls the GetQuartiles method.
if (customTotalName == "Quartiles") {
return GetQuartiles(values);

2013 DevExpress Inc.

1880

Products

1881
}
// Otherwise, returns a null value.
return null;
}
// Calculates a median for the specified sorted sample.
private decimal GetMedian(ArrayList values) {
if ((values.Count % 2) == 0) {
return ((decimal)(values[values.Count / 2 - 1]) +
(decimal)(values[values.Count / 2])) / 2;
}
else {
return (decimal)values[values.Count / 2];
}
}
// Calculates the first and third quartiles for the specified sorted sample
// and returns them inside a formatted string.
private string GetQuartiles(ArrayList values) {
ArrayList part1 = new ArrayList();
ArrayList part2 = new ArrayList();
if ((values.Count % 2) == 0) {
part1 = values.GetRange(0, values.Count / 2);
part2 = values.GetRange(values.Count / 2, values.Count / 2);
}
else {
part1 = values.GetRange(0, values.Count / 2 + 1);
part2 = values.GetRange(values.Count / 2, values.Count / 2 + 1);
}
return string.Format("({0}, {1})",
GetMedian(part1).ToString("c2"),
GetMedian(part2).ToString("c2"));
}

}
}
Visual Basic

C opy C ode

(Form1.vb)
Imports Microsoft.VisualBasic
Imports System
Imports System.Collections
Imports System.Windows.Forms
Imports DevExpress.Data.PivotGrid
Imports DevExpress.XtraPivotGrid
Namespace XtraPivotGrid_MultipleCustomTotals
Partial Public Class Form1
Inherits Form
Public Sub New()
InitializeComponent()
End Sub
Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.Load
' Binds the pivot grid to data.
Dim adapter As New nwindDataSetTableAdapters.ProductReportsTableAdapter()
pivotGridControl1.DataSource = adapter.GetData()
' Creates a PivotGridCustomTotal object that defines the Median Custom Total.
Dim medianCustomTotal As New PivotGridCustomTotal(PivotSummaryType.Custom)
' Specifies a unique PivotGridCustomTotal.Tag property value
' that will be used to distinguish between two Custom Totals.
medianCustomTotal.Tag = "Median"
' Specifies formatting settings that will be used to display
' Custom Total column/row headers.
medianCustomTotal.Format.FormatString = "{0} Median"
medianCustomTotal.Format.FormatType = DevExpress.Utils.FormatType.Custom
2013 DevExpress Inc.

1881

Products

1882
' Adds the Median Custom Total for the Category Name field.
fieldCategoryName.CustomTotals.Add(medianCustomTotal)
' Creates a PivotGridCustomTotal object that defines the Quartiles Custom Total.
Dim quartileCustomTotal As New PivotGridCustomTotal(PivotSummaryType.Custom)
' Specifies a unique PivotGridCustomTotal.Tag property value
' that will be used to distinguish between two Custom Totals.
quartileCustomTotal.Tag = "Quartiles"
' Specifies formatting settings that will be used to display
' Custom Total column/row headers.
quartileCustomTotal.Format.FormatString = "{0} Quartiles"
quartileCustomTotal.Format.FormatType = DevExpress.Utils.FormatType.Custom
' Adds the Quartiles Custom Total for the Category Name field.
fieldCategoryName.CustomTotals.Add(quartileCustomTotal)
' Enables the Custom Totals to be displayed instead of Automatic Totals.
fieldCategoryName.TotalsVisibility = PivotTotalsVisibility.CustomTotals
End Sub
' Handles the CustomCellValue event.
' Fires for each data cell. If the processed cell is a Custom Total,
' provides an appropriate Custom Total value.
Private Sub pivotGridControl1_CustomCellValue(ByVal sender As Object, _
ByVal e As PivotCellValueEventArgs) _
Handles pivotGridControl1.CustomCellValue
' Exits if the processed cell does not belong to a Custom Total.
If e.ColumnCustomTotal Is Nothing AndAlso e.RowCustomTotal Is Nothing Then
Return
End If
' Obtains a list of summary values against which
' the Custom Total will be calculated.
Dim summaryValues As ArrayList = GetSummaryValues(e)
' Obtains the name of the Custom Total that should be calculated.
Dim customTotalName As String = GetCustomTotalName(e)
' Calculates the Custom Total value and assigns it to the Value event parameter.
e.Value = GetCustomTotalValue(summaryValues, customTotalName)
End Sub
' Returns the Custom Total name.
Private Function GetCustomTotalName(ByVal e As PivotCellValueEventArgs) As String
Return If(e.ColumnCustomTotal IsNot Nothing, _
e.ColumnCustomTotal.Tag.ToString(), _
e.RowCustomTotal.Tag.ToString())
End Function
' Returns a list of summary values against which
' a Custom Total will be calculated.
Private Function GetSummaryValues(ByVal e As PivotCellValueEventArgs) As ArrayList
Dim values As New ArrayList()
' Creates a summary data source.
Dim sds As PivotSummaryDataSource = e.CreateSummaryDataSource()
' Iterates through summary data source records
' and copies summary values to an array.
For i As Integer = 0 To sds.RowCount - 1
Dim value As Object = sds.GetValue(i, e.DataField)
If value Is Nothing Then
Continue For
End If
values.Add(value)
Next i
' Sorts summary values.
values.Sort()
' Returns the summary values array.
Return values
End Function
' Returns the Custom Total value by an array of summary values.

2013 DevExpress Inc.

1882

Products

1883

Private Function GetCustomTotalValue(ByVal values As ArrayList, _


ByVal customTotalName As String) As Object
' Returns a null value if the provided array is empty.
If values.Count = 0 Then
Return Nothing
End If
' If the Median Custom Total should be calculated,
' calls the GetMedian method.
If customTotalName = "Median" Then
Return GetMedian(values)
End If
' If the Quartiles Custom Total should be calculated,
' calls the GetQuartiles method.
If customTotalName = "Quartiles" Then
Return GetQuartiles(values)
End If
' Otherwise, returns a null value.
Return Nothing
End Function
' Calculates a median for the specified sorted sample.
Private Function GetMedian(ByVal values As ArrayList) As Decimal
If (values.Count Mod 2) = 0 Then
Return (CDec(values(values.Count / 2 - 1)) + CDec(values(values.Count / 2))) / 2
Else
Return CDec(values(values.Count / 2))
End If
End Function
' Calculates the first and third quartiles for the specified sorted sample
' and returns them inside a formatted string.
Private Function GetQuartiles(ByVal values As ArrayList) As String
Dim part1 As New ArrayList()
Dim part2 As New ArrayList()
If (values.Count Mod 2) = 0 Then
part1 = values.GetRange(0, values.Count / 2)
part2 = values.GetRange(values.Count / 2, values.Count / 2)
Else
part1 = values.GetRange(0, values.Count / 2 + 1)
part2 = values.GetRange(values.Count / 2, values.Count / 2 + 1)
End If
Return String.Format("({0}, {1})", _
GetMedian(part1).ToString("c2"), _
GetMedian(part2).ToString("c2"))
End Function
End Class
End Namespace

2013 DevExpress Inc.

1883

Products

1884

How to: Group Date-Time Values


W inForms Controls > Products > Pivot Grid > Examples > Data-Related Features > How to: Group Date-Time
Values
Assume that the XtraPivotGrid control is bound to a data table which contains an 'OrderDate' field. In the follow ing
example tw o PivotGridField fields are created and displayed in the Column Header Area, each is bound to the
'OrderDate' field. The first PivotGridControl field's values will be grouped by years, the second field's values will be
grouped by months. To group data the PivotGridFieldBase.GroupInterval property is used.
The result of the code is shown below:

C#

C opy C ode

using DevExpress.XtraPivotGrid;
// Create column fields and bind them to the 'OrderDate' datasource field.
PivotGridField fieldYear = new PivotGridField("OrderDate", PivotArea.ColumnArea);
PivotGridField fieldMonth = new PivotGridField("OrderDate", PivotArea.ColumnArea);
// Add the fields to the field collection.
pivotGridControl1.Fields.Add(fieldYear);
pivotGridControl1.Fields.Add(fieldMonth);
// Set the caption and group mode of the fields.
fieldYear.GroupInterval = PivotGroupInterval.DateYear;
fieldYear.Caption = "Year";
fieldMonth.GroupInterval = PivotGroupInterval.DateMonth;
fieldMonth.Caption = "Month";
Visual Basic

C opy C ode

Imports DevExpress.XtraPivotGrid
' Create column fields and bind them to the 'OrderDate' datasource field.
Dim fieldYear As PivotGridField = New PivotGridField("OrderDate", PivotArea.ColumnArea)
Dim fieldMonth As PivotGridField = New PivotGridField("OrderDate", PivotArea.ColumnArea)
' Add the fields to the field collection.
pivotGridControl1.Fields.Add(fieldYear)
pivotGridControl1.Fields.Add(fieldMonth)
' Set the caption and group mode of the fields.
fieldYear.GroupInterval = PivotGroupInterval.DateYear
fieldYear.Caption = "Year"
fieldMonth.GroupInterval = PivotGroupInterval.DateMonth
fieldMonth.Caption = "Month"

2013 DevExpress Inc.

1884

Products

1885

How to: Implement Custom Group Intervals


W inForms Controls > Products > Pivot Grid > Examples > Data-Related Features > How to: Implement Custom
Group Intervals
The follow ing example shows how to custom group field values via the PivotGridControl.CustomGroupInterval
event.
In the example, the PivotGridControl's data source contains a ProductName field. The custom grouping algorithm
combines this field's values by the starting characters of values into three large ranges: A-E, F-S, and T-Z.
The follow ing image shows the result. The PivotGridControl contains tw o row fields bound to the same
ProductName data source field, named Product Group and Product respectively. The custom grouping feature is
applied only to the first field.

C#

C opy C ode

protected void PivotGridControl_CustomGroupInterval(object sender,


PivotCustomGroupIntervalEventArgs e) {
if (e.Field.Caption != "Product Group") return;
if (Convert.ToChar(e.Value.ToString()[0]) < 'F') {
e.GroupValue = "A-E";
return;
}
if (Convert.ToChar(e.Value.ToString()[0]) > 'E' &&
Convert.ToChar(e.Value.ToString()[0]) < 'T') {
e.GroupValue = "F-S";
return;
}
if (Convert.ToChar(e.Value.ToString()[0]) > 'S')
e.GroupValue = "T-Z";
}
Visual Basic

C opy C ode

Protected Sub PivotGridControl_CustomGroupInterval(ByVal sender As Object, _


ByVal e As PivotCustomGroupIntervalEventArgs) _
Handles pivotGridControl.CustomGroupInterval
If e.Field.Caption <> "Product Group" Then Return
If Convert.ToChar(e.Value.ToString().Chars(0)) < "F"c Then
e.GroupValue = "A-E"
Return
End If
If Convert.ToChar(e.Value.ToString().Chars(0)) > "E"c _

2013 DevExpress Inc.

1885

Products

1886

AndAlso Convert.ToChar(e.Value.ToString().Chars(0)) < "T"c Then


e.GroupValue = "F-S"
Return
End If
If Convert.ToChar(e.Value.ToString().Chars(0)) > "S"c Then
e.GroupValue = "T-Z"
End If
End Sub

2013 DevExpress Inc.

1886

Products

1887

How to: Implement the Sort by Summary Feature


W inForms Controls > Products > Pivot Grid > Examples > Data-Related Features > How to: Implement the Sort by
Summary Feature
This example demonstrates how to sort the values of a 'Sales Person' column field by summary values calculated
against an 'Order Amount' data field. To do this, the PivotGridFieldSortBySummaryInfo.Field property of the 'Sales
Person' field is set to reference the 'Order Amount' field. As a result the values will be arranged in the order
specified by the summary values.
The follow ing images show the XtraPivotGrid control before and after the field values are sorted by the summary
values.
Before:

After:

C#

C opy C ode

pivotGridControl1.Fields["Sales Person"].SortBySummaryInfo.Field =
pivotGridControl1.Fields["Order Amount"];
Visual Basic

C opy C ode

PivotGridControl1.Fields("Sales Person").SortBySummaryInfo.Field = _
PivotGridControl1.Fields("Order Amount")

2013 DevExpress Inc.

1887

Products

1888

How to: Sort Data by Columns (Rows) in Code


W inForms Controls > Products > Pivot Grid > Examples > Data-Related Features > How to: Sort Data by Columns
(Rows) in Code
In a PivotGridControl, values of a specific row field can be sorted by values in a grand total column or any other
column. Similarly, values of a specific column field can be sorted by values in a grand total row or any other row .
The follow ing example shows how to sort a row field's data by a column's values. To sort data, the
PivotGridFieldBase.SortBySummaryInfo property is used.
Consider the follow ing layout:

1.To sort values of the Product Name row field by values of the "Grand Total" column calculated against
the Extended Price data field, use the following code:
C#

C opy C ode

fieldProductName.SortBySummaryInfo.Conditions.Clear();
fieldProductName.SortBySummaryInfo.Field = fieldExtendedPrice;
The result is displayed below :

2.To sort values of the Product Name row field by values of the "1994 Total" column calculated against the
Extended Price data field, use the following code:
C#

C opy C ode

fieldProductName.SortBySummaryInfo.Field = fieldExtendedPrice;
fieldProductName.SortBySummaryInfo.Conditions.Clear();
fieldProductName.SortBySummaryInfo.Conditions.Add(new PivotGridFieldSortCondition(fieldOrderDa
The result is displayed below :

2013 DevExpress Inc.

1888

Products

1889

3.To sort values of the Product Name row field by values of the "1994 - USA" column calculated against
the Extended Price data field, use the following code:
C#

C opy C ode

fieldProductName.SortBySummaryInfo.Field = fieldExtendedPrice;
fieldProductName.SortBySummaryInfo.Conditions.Clear();
fieldProductName.SortBySummaryInfo.Conditions.Add(new PivotGridFieldSortCondition(fieldOrderDa
fieldProductName.SortBySummaryInfo.Conditions.Add(new PivotGridFieldSortCondition(fieldCountry
The result is displayed below :

2013 DevExpress Inc.

1889

Products

1890

How to: Sort Data by Columns (Rows) in OLAP Mode


W inForms Controls > Products > Pivot Grid > Examples > Data-Related Features > How to: Sort Data by Columns
(Rows) in OLAP Mode
Show Me
The complete sample project is available in the DevExpress Code Central database at http://w ww .devexpress.com/
example=E3023. Depending on the target platform type (ASP.NET, W inForms, etc), you can either run this example
online or dow nload an auto-executable sample.
The follow ing example demonstrates how to implement Sorting by Summary in OLAP mode.
In this example, values of the Semester field are sorted by the Australia | Bendigo column summary values. To do
this, tw o sort conditions represented by PivotGridFieldSortCondition instances are created. One of them
represents an OLAP member that corresponds to the 'Australia' value, while another corresponds to the 'Bendigo'
value. These sort conditions are added to the Semester field's PivotGridFieldSortBySummaryInfo.Conditions
collection to specify the column by which Semester values should be sorted. A data field that identifies the column
is specified via the PivotGridFieldSortBySummaryInfo.Field property.
OLAP members corresponding to the Australia and Bendigo values are obtained using the PivotGridControl.
GetFieldValueOLAPMember method. Note that OLAP members can be obtained only for visible field values. For this
reason, the Australia field value is expanded before initializing OLAP members in order to obtain the Bendigo OLAP
member.
This sample uses the Adventure W orks 2008 cube.
C#

C opy C ode

(Form1.cs)
using System;
using System.Windows.Forms;
using DevExpress.XtraPivotGrid;
namespace XtraPivotGrid_OLAPSortBySummary {
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e) {
// Expands the Australia column to be able to retrieve OLAP members
// that correspond to the nested columns.
pivotGridControl1.ExpandValue(true, new object[] { "Australia" });
// Obtains OLAP members corresponding to the Australia and Bendigo values.
IOLAPMember countryMember = pivotGridControl1.GetFieldValueOLAPMember(fieldCountry, 0);
IOLAPMember cityMember = pivotGridControl1.GetFieldValueOLAPMember(fieldCity, 0);
// Exits if the OLAP members were not obtained successfully.
if (countryMember == null || cityMember == null)
return;
// Locks the pivot grid from updating while the Sort by Summary
// settings are being customized.
pivotGridControl1.BeginUpdate();
try {
// Specifies a data field whose summary values should be used to sort values
// of the Fiscal Year field.
fieldFiscalYear.SortBySummaryInfo.Field = fieldInternetSalesAmount;
// Specifies a column by which the Fiscal Year field values should be sorted.
fieldFiscalYear.SortBySummaryInfo.Conditions.Add(
new PivotGridFieldSortCondition(fieldCountry, "Australia", countryMember.UniqueName
fieldFiscalYear.SortBySummaryInfo.Conditions.Add(
new PivotGridFieldSortCondition(fieldCity, "Bendigo", cityMember.UniqueName));
}
finally {
// Unlocks the pivot grid and applies changes.
pivotGridControl1.EndUpdate();
}

2013 DevExpress Inc.

1890

Products

1891
}

}
}
Visual Basic

C opy C ode

(Form1.vb)
Imports Microsoft.VisualBasic
Imports System
Imports System.Windows.Forms
Imports DevExpress.XtraPivotGrid
Namespace XtraPivotGrid_OLAPSortBySummary
Partial Public Class Form1
Inherits Form
Public Sub New()
InitializeComponent()
End Sub
Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.Load
' Expands the Australia column to be able to retrieve OLAP members
' that correspond to the nested columns.
pivotGridControl1.ExpandValue(True, New Object() { "Australia" })
' Obtains OLAP members corresponding to the Australia and Bendigo values.
Dim countryMember As IOLAPMember = _
pivotGridControl1.GetFieldValueOLAPMember(fieldCountry, 0)
Dim cityMember As IOLAPMember = _
pivotGridControl1.GetFieldValueOLAPMember(fieldCity, 0)
' Exits if the OLAP members were not obtained successfully.
If countryMember Is Nothing OrElse cityMember Is Nothing Then
Return
End If
' Locks the pivot grid from updating while the Sort by Summary
' settings are being customized.
pivotGridControl1.BeginUpdate()
Try
' Specifies a data field whose summary values should be used to sort values
' of the Fiscal Year field.
fieldFiscalYear.SortBySummaryInfo.Field = fieldInternetSalesAmount
' Specifies a column by which the Fiscal Year field values should be sorted.
fieldFiscalYear.SortBySummaryInfo.Conditions.Add( _
New PivotGridFieldSortCondition(fieldCountry, "Australia", countryMember.UniqueName
fieldFiscalYear.SortBySummaryInfo.Conditions.Add( _
New PivotGridFieldSortCondition(fieldCity, "Bendigo", cityMember.UniqueName))
Finally
' Unlocks the pivot grid and applies changes.
pivotGridControl1.EndUpdate()
End Try
End Sub
End Class
End Namespace

2013 DevExpress Inc.

1891

Products

1892

How to: Apply Filter to a Field


W inForms Controls > Products > Pivot Grid > Examples > Data-Related Features > How to: Apply Filter to a Field
The follow ing example shows how to apply a filter to a field. The filter w ill select those records w hich contain
'Brazil' or 'USA' in the 'Country' field.
C#

C opy C ode

using DevExpress.XtraPivotGrid;
PivotGridField field = pivotGridControl1.Fields["Country"];
// Lock the control to prevent excessive updates when multiple properties are modified.
pivotGridControl1.BeginUpdate();
try {
// Clear the filter value collection and add two items to it.
field.FilterValues.Clear();
field.FilterValues.Add("Brazil");
field.FilterValues.Add("USA");
// Specify that the control should only display the records
// which contain the specified values in the Country field.
field.FilterValues.FilterType = DevExpress.Data.PivotGrid.PivotFilterType.Included;
}
finally {
// Unlock the control.
pivotGridControl1.EndUpdate();
}
Visual Basic

C opy C ode

Imports DevExpress.XtraPivotGrid
Dim field As PivotGridField = PivotGridControl1.Fields("Country")
' Lock the control to prevent excessive updates when multiple properties are modified.
PivotGridControl1.BeginUpdate()
Try
' Clear the filter value collection and add two items to it.
field.FilterValues.Clear()
field.FilterValues.Add("Brazil")
field.FilterValues.Add("USA")
' Specify that the control should only display the records
' which contain the specified values in the Country field.
field.FilterValues.FilterType = DevExpress.Data.PivotGrid.PivotFilterType.Included
Finally
' Unlock the control.
PivotGridControl1.EndUpdate()
End Try

2013 DevExpress Inc.

1892

Products

1893

How to: Apply Summary Filter


W inForms Controls > Products > Pivot Grid > Examples > Data-Related Features > How to: Apply Summary Filter
Show Me
The complete sample project is available in the DevExpress Code Central database at http://w ww .devexpress.com/
example=E4390. Depending on the target platform type (ASP.NET, W inForms, etc), you can either run this example
online or dow nload an auto-executable sample.
The follow ing example shows how to apply a summary filter to PivotGridControl data that belongs to a particular
aggregation level.
In this example, PivotGridControl displays product sales by country. The summary filter is applied to country totals
calculated for individual products, so that only values that fall into the range from 500 to 2500 are included.
The range of included values is specified using the PivotSummaryFilter.StartValue and PivotSummaryFilter.
EndValue properties. To enable filtering only for the selected aggregation level, the PivotSummaryFilter.Mode
property is set to PivotSummaryFilterMode.SpecificLevel. To identify this level, the PivotSummaryFilter.RowField
and PivotSummaryFilter.ColumnField properties are set to fieldProductName and fieldCountry respectively.
C#

C opy C ode

(Form1.cs)
using System;
using System.Windows.Forms;
using DevExpress.XtraPivotGrid;
namespace XtraPivotGrid_ApplySummaryFilter {
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e) {
// Binds the pivot grid to data.
this.salesPersonTableAdapter.Fill(this.nwindDataSet.SalesPerson);
// Locks the control to prevent excessive updates when multiple properties are modified.
pivotGridControl1.BeginUpdate();
try {
// Sets the minimum summary value to be displayed.
fieldExtendedPrice.SummaryFilter.StartValue = 500;
// Sets the maximum summary value to be displayed.
fieldExtendedPrice.SummaryFilter.EndValue = 2500;
// Specifies that summary filtering should be applied
// to a particular aggregation level.
fieldExtendedPrice.SummaryFilter.Mode = PivotSummaryFilterMode.SpecificLevel;
// Sets the row used to identify an aggregation level
// to which the filtering is applied.
fieldExtendedPrice.SummaryFilter.RowField = fieldProductName;
// Sets the column used to identify an aggregation level
// to which the filtering is applied.
fieldExtendedPrice.SummaryFilter.ColumnField = fieldCountry;
}
finally {
// Unlocks the control.
pivotGridControl1.EndUpdate();
}
}
}
}
Visual Basic

C opy C ode

(Form1.vb)
Imports Microsoft.VisualBasic
Imports System

2013 DevExpress Inc.

1893

Products

1894

Imports System.Windows.Forms
Imports DevExpress.XtraPivotGrid
Namespace XtraPivotGrid_ApplySummaryFilter
Partial Public Class Form1
Inherits Form
Public Sub New()
InitializeComponent()
End Sub
Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.Load
' Binds the pivot grid to data.
Me.salesPersonTableAdapter.Fill(Me.nwindDataSet.SalesPerson)
' Locks the control to prevent excessive updates when multiple properties are modified.
pivotGridControl1.BeginUpdate()
Try
' Sets the minimum summary value to be displayed.
fieldExtendedPrice.SummaryFilter.StartValue = 500
' Sets the maximum summary value to be displayed.
fieldExtendedPrice.SummaryFilter.EndValue = 2500
' Specifies that summary filtering should be applied
' to a particular aggregation level.
fieldExtendedPrice.SummaryFilter.Mode = PivotSummaryFilterMode.SpecificLevel
' Sets the row used to identify an aggregation level
' to which the filtering is applied.
fieldExtendedPrice.SummaryFilter.RowField = fieldProductName
' Sets the column used to identify an aggregation level
' to which the filtering is applied.
fieldExtendedPrice.SummaryFilter.ColumnField = fieldCountry
Finally
' Unlocks the control.
pivotGridControl1.EndUpdate()
End Try
End Sub
End Class
End Namespace

2013 DevExpress Inc.

1894

Products

1895

How to: Prevent End-Users From Changing Filter Conditions


W inForms Controls > Products > Pivot Grid > Examples > Data-Related Features > How to: Prevent End-Users
From Changing Filter Conditions
Show Me
The complete sample project is available in the DevExpress Code Central database at http://w ww .devexpress.com/
example=E2397. Depending on the target platform type (ASP.NET, W inForms, etc), you can either run this example
online or dow nload an auto-executable sample.
The follow ing example shows how to prevent end-users from changing the filter condition.
In this example, the FieldFilterChanging event is handled to prevent an end-user from hiding the 'Beverages' field
value. If an end-user tries to hide the 'Beverages' field value, the event handler sets the event parameter's
Cancel property to true to cancel changing the filter condition.
C#

C opy C ode

(Program.cs)
using System;
using System.Collections.Generic;
using System.Windows.Forms;
namespace EmptyWinApp {
static class Program {
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main() {
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
C#

C opy C ode

(Form1.cs)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.Data.PivotGrid;
using DevExpress.XtraPivotGrid;
using DevExpress.XtraPivotGrid.Data;
namespace EmptyWinApp {
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e) {
this.productReportsTableAdapter.Fill(this.productReports._ProductReports);
}
private void pivotGridControl1_FieldFilterChanging(object sender,
PivotFieldFilterChangingEventArgs e) {
if(object.ReferenceEquals(e.Field, fieldCategoryName)) {
if((e.Field.FilterValues.FilterType == PivotFilterType.Excluded &&
e.Values.Contains("Beverages")) ||
(e.Field.FilterValues.FilterType == PivotFilterType.Included &&
!e.Values.Contains("Beverages"))) {

2013 DevExpress Inc.

1895

Products

1896
MessageBox.Show("You are not allowed to hide the 'Beverages' value.");
e.Cancel = true;
}
}
}

}
}
Visual Basic

C opy C ode

(Form1.vb)
Imports Microsoft.VisualBasic
Imports System
Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.Data
Imports System.Drawing
Imports System.Text
Imports System.Windows.Forms
Imports DevExpress.Data.PivotGrid
Imports DevExpress.XtraPivotGrid
Imports DevExpress.XtraPivotGrid.Data
Namespace EmptyWinApp
Partial Public Class Form1
Inherits Form
Public Sub New()
InitializeComponent()
End Sub
Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.Load
Me.productReportsTableAdapter.Fill(Me.productReports._ProductReports)
End Sub
Private Sub pivotGridControl1_FieldFilterChanging(ByVal sender As Object, _
ByVal e As PivotFieldFilterChangingEventArgs) _
Handles pivotGridControl1.FieldFilterChanging
If Object.ReferenceEquals(e.Field, fieldCategoryName) Then
If (e.Field.FilterValues.FilterType = PivotFilterType.Excluded AndAlso _
e.Values.Contains("Beverages")) OrElse _
(e.Field.FilterValues.FilterType = PivotFilterType.Included AndAlso _
(Not e.Values.Contains("Beverages"))) Then
MessageBox.Show("You are not allowed to hide the 'Beverages' value.")
e.Cancel = True
End If
End If
End Sub
End Class
End Namespace
Visual Basic

C opy C ode

(Program.vb)
Imports Microsoft.VisualBasic
Imports System
Imports System.Collections.Generic
Imports System.Windows.Forms
Namespace EmptyWinApp
Friend NotInheritable Class Program
''' <summary>
''' The main entry point for the application.
''' </summary>
Private Sub New()
End Sub
<STAThread> _
Shared Sub Main()
2013 DevExpress Inc.

1896

Products

1897

Application.EnableVisualStyles()
Application.SetCompatibleTextRenderingDefault(False)
Application.Run(New Form1())
End Sub
End Class
End Namespace

2013 DevExpress Inc.

1897

Products

1898

How to: Add and Remove Items From Filter Drop-Down Lists
W inForms Controls > Products > Pivot Grid > Examples > Data-Related Features > How to: Add and Remove Items
From Filter Drop-Down Lists
Show Me
The complete sample project is available in the DevExpress Code Central database at http://w ww .devexpress.com/
example=E2396. Depending on the target platform type (ASP.NET, W inForms, etc), you can either run this example
online or dow nload an auto-executable sample.
The follow ing example shows how to add and remove items from the filter dropdow n list.
In this example, the 'Beverages' item is hidden from the filter dropdown list of the Category field, and a dummy
item is created and added to the list. To do this, the CustomFilterPopupItems event is handled. In the event
handler, the 'Beverages' item is removed from the event parameter's Items collection, and a new item ('Dummy
Item') is added to the collection.
C#

C opy C ode

(Form1.cs)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraPivotGrid;
using DevExpress.XtraPivotGrid.Data;
namespace EmptyWinApp {
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e) {
this.productReportsTableAdapter.Fill(this.productReports._ProductReports);
}
readonly object dummyItem = new object();
private void pivotGridControl1_CustomFilterPopupItems(object sender,
PivotCustomFilterPopupItemsEventArgs e) {
if(object.ReferenceEquals(e.Field, fieldCategoryName)) {
for(int i = e.Items.Count - 1; i >= 0; i--) {
if(object.Equals(e.Items[i].Value, "Beverages")) {
e.Items.RemoveAt(i);
break;
}
}
e.Items.Insert(0, new PivotGridFilterItem(dummyItem,
"Dummy Item",
e.Field.FilterValues.Contains(dummyItem)));
}
}
}
}
C#

C opy C ode

(Program.cs)
using System;
using System.Collections.Generic;
using System.Windows.Forms;
namespace EmptyWinApp {
static class Program {
/// <summary>

2013 DevExpress Inc.

1898

Products

1899
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main() {
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}

}
}
Visual Basic

C opy C ode

(Program.vb)
Imports Microsoft.VisualBasic
Imports System
Imports System.Collections.Generic
Imports System.Windows.Forms
Namespace EmptyWinApp
Friend NotInheritable Class Program
''' <summary>
''' The main entry point for the application.
''' </summary>
Private Sub New()
End Sub
<STAThread> _
Shared Sub Main()
Application.EnableVisualStyles()
Application.SetCompatibleTextRenderingDefault(False)
Application.Run(New Form1())
End Sub
End Class
End Namespace
Visual Basic

C opy C ode

(Form1.vb)
Imports Microsoft.VisualBasic
Imports System
Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.Data
Imports System.Drawing
Imports System.Text
Imports System.Windows.Forms
Imports DevExpress.XtraPivotGrid
Imports DevExpress.XtraPivotGrid.Data
Namespace EmptyWinApp
Partial Public Class Form1
Inherits Form
Public Sub New()
InitializeComponent()
End Sub
Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.Load
Me.productReportsTableAdapter.Fill(Me.productReports._ProductReports)
End Sub
Private ReadOnly dummyItem As Object = New Object()
Private Sub pivotGridControl1_CustomFilterPopupItems(ByVal sender As Object, _
ByVal e As PivotCustomFilterPopupItemsEventArgs) _
Handles pivotGridControl1.CustomFilterPopupItems
If Object.ReferenceEquals(e.Field, fieldCategoryName) Then
For i As Integer = e.Items.Count - 1 To 0 Step -1
If Object.Equals(e.Items(i).Value, "Beverages") Then
2013 DevExpress Inc.

1899

Products

1900

e.Items.RemoveAt(i)
Exit For
End If
Next i
e.Items.Insert(0, New PivotGridFilterItem(dummyItem, _
"Dummy Item", _
e.Field.FilterValues.Contains(dummyItem)))
End If
End Sub
End Class
End Namespace

2013 DevExpress Inc.

1900

Products

1901

How to: Implement Group Filter for a PivotGrid


W inForms Controls > Products > Pivot Grid > Examples > Data-Related Features > How to: Implement Group Filter
for a PivotGrid
Show Me
The complete sample project is available in the DevExpress Code Central database at http://w ww .devexpress.com/
example=E4581. Depending on the target platform type (ASP.NET, W inForms, etc), you can either run this example
online or dow nload an auto-executable sample.
This example demonstrates how to apply custom group filters to PivotGridControl data.
In this example, a filter type is defined by setting the PivotGroupFilterValues.FilterType property to PivotFilterType.
Included. To create and add group filter values to the PivotGroupFilterValues.Values and PivotGroupFilterValue.
ChildValues collections the PivotGroupFilterValuesCollection.Add method is used.
C#

C opy C ode

(Form1.cs)
using System;
using System.Windows.Forms;
using DevExpress.XtraPivotGrid;
namespace GroupFilter {
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e) {
// Binds the pivot grid to data.
this.salesPersonTableAdapter.Fill(this.nwindDataSet.SalesPerson);
// Gets the field group from the collection.
PivotGridGroup OrderDateGroup = pivotGridControl1.Groups[0];
// Locks the PivotGroupFilterValues object by disabling visual updates.
OrderDateGroup.FilterValues.BeginUpdate();
// Sets the filter type.
// It specifies that the PivotGridControl should display only filter values.
OrderDateGroup.FilterValues.FilterType = PivotFilterType.Included;
// Creates a filter value and adds it to the PivotGroupFilterValues.Values collection.
OrderDateGroup.FilterValues.Values.Add(new PivotGroupFilterValue(1994));
// Creates a filter value and adds it to the PivotGroupFilterValues.Values collection.
// Then creates a child value of the filter value and adds it to the parent value collectio
OrderDateGroup.FilterValues.Values.Add(1995).ChildValues.Add(1);
// Unlocks the PivotGroupFilterValues object.
OrderDateGroup.FilterValues.EndUpdate();
}
}
}
Visual Basic

C opy C ode

(Form1.vb)
Imports Microsoft.VisualBasic
Imports System
Imports System.Windows.Forms
Imports DevExpress.XtraPivotGrid
Namespace GroupFilter
Partial Public Class Form1
Inherits Form
Public Sub New()
InitializeComponent()
End Sub
Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.Load
' Binds the pivot grid to data.
Me.salesPersonTableAdapter.Fill(Me.nwindDataSet.SalesPerson)

2013 DevExpress Inc.

1901

Products

1902

' Gets the field group from the collection.


Dim OrderDateGroup As PivotGridGroup = pivotGridControl1.Groups(0)
' Locks the PivotGroupFilterValues object by disabling visual updates.
OrderDateGroup.FilterValues.BeginUpdate()
' Sets the filter type.
' It specifies that the PivotGridControl should display only filter values.
OrderDateGroup.FilterValues.FilterType = PivotFilterType.Included
' Creates a filter value and adds it to the PivotGroupFilterValues.Values collection.
OrderDateGroup.FilterValues.Values.Add(New PivotGroupFilterValue(1994))
' Creates a filter value and adds it to the PivotGroupFilterValues.Values collection.
' Then creates a child value of the filter value and adds it to the parent value collection
OrderDateGroup.FilterValues.Values.Add(1995).ChildValues.Add(1)
' Unlocks the PivotGroupFilterValues object.
OrderDateGroup.FilterValues.EndUpdate()
End Sub
End Class
End Namespace

2013 DevExpress Inc.

1902

Products

1903

How to: Change the Prefilter Criteria in Code


W inForms Controls > Products > Pivot Grid > Examples > Data-Related Features > How to: Change the Prefilter
Criteria in Code
The follow ing code shows how to filter a PivotGrid control's underlying data source using the Prefilter. The filter
selects records that contain 'USA' or 'UK' strings in the Country field.
C#

C opy C ode

using DevExpress.Data.Filtering;
//...
pivotgridControl1.Prefilter.CriteriaString = "[" + fieldCountry.PrefilterColumnName +
"] == 'UK' OR [" + fieldCountry.PrefilterColumnName + "] == 'USA'";
Visual Basic

C opy C ode

Imports DevExpress.Data.Filtering
'...
PivotGridControl1.Prefilter.CriteriaString = "[" + FieldCountry.PrefilterColumnName +
"] == 'UK' OR [" + FieldCountry.PrefilterColumnName + "] == 'USA'"

2013 DevExpress Inc.

1903

Products

1904

How to: Use Asynchronous Operations That Return the Result


W inForms Controls > Products > Pivot Grid > Examples > Data-Related Features > How to: Use Asynchronous
Operations That Return the Result
Show Me
The complete sample project is available in the DevExpress Code Central database at http://w ww .devexpress.com/
example=E4567. Depending on the target platform type (ASP.NET, W inForms, etc), you can either run this example
online or dow nload an auto-executable sample.
This example show s how to use asynchronous operations that return the result.
In this example, the PivotGridControl.CellClick event is handled to generate a drill-down data source for a specific
cell using the PivotGridControl.CreateDrillDownDataSourceAsync method. The AsyncCompletedHandler delegate is
passed as a method parameter. The referenced method is executed after the operation is completed, allow ing to
obtain the result via the
parameter of the delegate. This parameter returns an AsyncOperationResult
instance.
The AsyncOperationResult.Value property is used to obtain a record set associated with the clicked cell. Then, the
PivotDrillDownDataSource.Row Count property is used to determine the number of records in the data source for
this cell.
C#

C opy C ode

(Form1.cs)
using System;
using System.Windows.Forms;
using DevExpress.XtraPivotGrid;
namespace XtraPivotGrid_CreateDrillDownDataSourceAsync {
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e) {
// Binds the pivot grid to data.
this.salesPersonTableAdapter.Fill(this.nwindDataSet.SalesPerson);
}
private void pivotGridControl1_CellClick(object sender,
DevExpress.XtraPivotGrid.PivotCellEventArgs e) {
//Checks whether an asynchronous operation is in progress.
if (!pivotGridControl1.IsAsyncInProgress)
// Gets the record set associated with the clicked cell.
// The delegate is passed to obtain this record set.
pivotGridControl1.CreateDrillDownDataSourceAsync(e.ColumnIndex, e.RowIndex, result => {
// The 'result' parameter of the delegate returns an AsyncOperationResult instance.
// The AsyncOperationResult.Value property is used to obtain the record set,
// the PivotDrillDownDataSource.RowCount property is used to obtain the number
// of records in the data source.
label1.Text = "RowCount = " + ((PivotDrillDownDataSource)result.Value).RowCount;
});
}
}
}
Visual Basic

C opy C ode

(Form1.vb)
Imports Microsoft.VisualBasic
Imports System
Imports System.Windows.Forms
Imports DevExpress.XtraPivotGrid
Namespace XtraPivotGrid_CreateDrillDownDataSourceAsync
Partial Public Class Form1
Inherits Form

2013 DevExpress Inc.

1904

Products

1905

Public Sub New()


InitializeComponent()
End Sub
Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.Load
' Binds the pivot grid to data.
Me.salesPersonTableAdapter.Fill(Me.nwindDataSet.SalesPerson)
End Sub
Private Sub pivotGridControl1_CellClick( _
ByVal sender As Object, ByVal e As DevExpress.XtraPivotGrid.PivotCellEventArgs) _
Handles pivotGridControl1.CellClick
'Checks whether an asynchronous operation is in progress.
If (Not pivotGridControl1.IsAsyncInProgress) Then
' Gets the record set associated with the clicked cell.
' The delegate is passed to obtain this record set.
' The 'result' parameter of the delegate returns an AsyncOperationResult instance.
' The AsyncOperationResult.Value property is used to obtain the record set,
' the PivotDrillDownDataSource.RowCount property is used to obtain the number
' of records in the data source.
pivotGridControl1.CreateDrillDownDataSourceAsync( _
e.ColumnIndex, e.RowIndex, Function(result) AnonymousMethod1(result))
End If
End Sub
Private Function AnonymousMethod1(ByVal result As Object) As Boolean
label1.Text = "RowCount = " & (CType(result.Value, PivotDrillDownDataSource)).RowCount
Return True
End Function
End Class
End Namespace

2013 DevExpress Inc.

1905

Products

1906

How to: Sort Filter Drop-Down Items in a Custom Manner


W inForms Controls > Products > Pivot Grid > Examples > Data-Related Features > How to: Sort Filter Drop-Dow n
Items in a Custom Manner
Show Me
The complete sample project is available in the DevExpress Code Central database at http://w ww .devexpress.com/
example=E2682. Depending on the target platform type (ASP.NET, W inForms, etc), you can either run this example
online or dow nload an auto-executable sample.
The follow ing example demonstrates how to sort filter drop-down items in a custom manner.In this example, the
CustomFilterPopupItems event is handled to manage a list of filter items. This event is raised w hen an end-user
invokes the filter drop-dow n. The event parameter provides access to the filter items list, w hich is then sorted by
the length of the items' captions (if the corresponding option is selected).
C#

C opy C ode

(Form1.cs)
using System;
using System.Collections;
using System.Windows.Forms;
using DevExpress.XtraPivotGrid;
using DevExpress.XtraPivotGrid.Data;
namespace XtraPivotGrid_ExampleTemplate {
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e) {
DataSet1TableAdapters.ProductReportsTableAdapter tableAdapter =
new DataSet1TableAdapters.ProductReportsTableAdapter();
pivotGridControl1.DataSource = tableAdapter.GetData();
pivotGridControl1.BestFit();
}
private void pivotGridControl1_CustomFilterPopupItems(object sender,
PivotCustomFilterPopupItemsEventArgs e) {
if(rbCaptionLength.Checked)
ArrayList.Adapter((IList)e.Items).Sort(new FilterItemsComparer());
}
private void rbAlphabeticalSort_CheckedChanged(object sender, EventArgs e) {
fieldProductName.ShowFilterPopup();
}
}
public class FilterItemsComparer : IComparer {
int IComparer.Compare(object x, object y) {
if (!(x is PivotGridFilterItem) || !(y is PivotGridFilterItem)) return 0;
PivotGridFilterItem item1 = (PivotGridFilterItem)x;
PivotGridFilterItem item2 = (PivotGridFilterItem)y;
if (item1.ToString().Length == item2.ToString().Length) return 0;
if (item1.ToString().Length > item2.ToString().Length) return 1;
return -1;
}
}
}
Visual Basic

C opy C ode

(Form1.vb)
Imports Microsoft.VisualBasic
Imports System
Imports System.Collections
Imports System.Windows.Forms
Imports DevExpress.XtraPivotGrid

2013 DevExpress Inc.

1906

Products

1907

Imports DevExpress.XtraPivotGrid.Data
Namespace XtraPivotGrid_ExampleTemplate
Partial Public Class Form1
Inherits Form
Public Sub New()
InitializeComponent()
End Sub
Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.Load
Dim tableAdapter As New DataSet1TableAdapters.ProductReportsTableAdapter()
pivotGridControl1.DataSource = tableAdapter.GetData()
pivotGridControl1.BestFit()
End Sub
Private Sub pivotGridControl1_CustomFilterPopupItems(ByVal sender As Object, _
ByVal e As PivotCustomFilterPopupItemsEventArgs) _
Handles pivotGridControl1.CustomFilterPopupItems
If rbCaptionLength.Checked Then
ArrayList.Adapter(CType(e.Items, IList)).Sort(New FilterItemsComparer())
End If
End Sub
Private Sub rbAlphabeticalSort_CheckedChanged(ByVal sender As Object, ByVal e As EventArgs) _
Handles rbAlphabeticalSort.CheckedChanged
fieldProductName.ShowFilterPopup()
End Sub
End Class
Public Class FilterItemsComparer
Implements IComparer
Private Function IComparer_Compare(ByVal x As Object, ByVal y As Object) As Integer _
Implements IComparer.Compare
If Not(TypeOf x Is PivotGridFilterItem) OrElse Not(TypeOf y Is PivotGridFilterItem) Then
Return 0
End If
Dim item1 As PivotGridFilterItem = CType(x, PivotGridFilterItem)
Dim item2 As PivotGridFilterItem = CType(y, PivotGridFilterItem)
If item1.ToString().Length = item2.ToString().Length Then
Return 0
End If
If item1.ToString().Length > item2.ToString().Length Then
Return 1
End If
Return -1
End Function
End Class
End Namespace

2013 DevExpress Inc.

1907

Products

1908

How to: Locate a Column (Row) Header By Its Column's (Row's) Summary Valu
W inForms Controls > Products > Pivot Grid > Examples > Data-Related Features > How to: Locate a Column (Row)
Header By Its Column's (Row's) Summary Values
Show Me
The complete sample project is available in the DevExpress Code Central database at http://w ww .devexpress.com/
example=E2772. Depending on the target platform type (ASP.NET, W inForms, etc), you can either run this example
online or dow nload an auto-executable sample.
The follow ing example demonstrates how to handle the CustomFieldValueCells event to locate a specific column/
row header identified by its column's/row's summary values.In this example, a predicate is used to locate a
column that contains only zero summary values. The column header is obtained by the event parameter's FindCell
method, and then removed via the Remove method.
C#

C opy C ode

(Form1.cs)
using System;
using System.Globalization;
using System.Windows.Forms;
using DevExpress.XtraPivotGrid;
namespace XtraPivotGrid_FindCells {
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
pivotGridControl1.CustomFieldValueCells +=
new PivotCustomFieldValueCellsEventHandler(pivotGrid_CustomFieldValueCells);
}
void Form1_Load(object sender, EventArgs e) {
PivotHelper.FillPivot(pivotGridControl1);
pivotGridControl1.DataSource = PivotHelper.GetDataTable();
pivotGridControl1.BestFit();
}
// Handles the CustomFieldValueCells event to remove columns with
// zero summary values.
protected void pivotGrid_CustomFieldValueCells(object sender,
PivotCustomFieldValueCellsEventArgs e) {
if (pivotGridControl1.DataSource == null) return;
if (radioGroup1.SelectedIndex == 0) return;
// Obtains the first encountered column header whose column
// matches the specified condition, represented by a predicate.
FieldValueCell cell = e.FindCell(true, new Predicate<object[]>(
// Defines the predicate returning true for columns
// that contain only zero summary values.
delegate(object[] dataCellValues) {
foreach (object value in dataCellValues) {
if (!object.Equals((decimal)0, value))
return false;
}
return true;
}));
// If any column header matches the condition, this column is removed.
if (cell != null) e.Remove(cell);
}
void pivotGridControl1_FieldValueDisplayText(object sender,
PivotFieldDisplayTextEventArgs e) {
if(e.Field == pivotGridControl1.Fields[PivotHelper.Month]) {
e.DisplayText = CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName((int)e.Value);
}
}
void radioGroup1_SelectedIndexChanged(object sender, EventArgs e) {
this.pivotGridControl1.LayoutChanged();
2013 DevExpress Inc.

1908

Products

1909
pivotGridControl1.BestFit();
}

}
}
Visual Basic

C opy C ode

(Form1.vb)
Imports Microsoft.VisualBasic
Imports System
Imports System.Globalization
Imports System.Windows.Forms
Imports DevExpress.XtraPivotGrid
Namespace XtraPivotGrid_FindCells
Partial Public Class Form1
Inherits Form
Public Sub New()
InitializeComponent()
AddHandler pivotGridControl1.CustomFieldValueCells, _
AddressOf pivotGrid_CustomFieldValueCells
End Sub
Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.Load
PivotHelper.FillPivot(pivotGridControl1)
pivotGridControl1.DataSource = PivotHelper.GetDataTable()
pivotGridControl1.BestFit()
End Sub
' Handles the CustomFieldValueCells event to remove columns with
' zero summary values.
Protected Sub pivotGrid_CustomFieldValueCells(ByVal sender As Object, _
ByVal e As PivotCustomFieldValueCellsEventArgs)
If pivotGridControl1.DataSource Is Nothing Then
Return
End If
If radioGroup1.SelectedIndex = 0 Then
Return
End If
' Obtains the first encountered column header whose column
' matches the specified condition, represented by a predicate.
Dim cell As FieldValueCell = _
e.FindCell(True, New Predicate(Of Object())(AddressOf AnonymousMethod1))
' If any column header matches the condition, this column is removed.
If cell IsNot Nothing Then
e.Remove(cell)
End If
End Sub
' Defines the predicate returning true for columns
' that contain only zero summary values.
Private Function AnonymousMethod1(ByVal dataCellValues() As Object) As Boolean
For Each value As Object In dataCellValues
If (Not Object.Equals(CDec(0), value)) Then
Return False
End If
Next value
Return True
End Function
Private Sub pivotGridControl1_FieldValueDisplayText(ByVal sender As Object, _
ByVal e As PivotFieldDisplayTextEventArgs) _
Handles pivotGridControl1.FieldValueDisplayText
If Object.Equals(e.Field, pivotGridControl1.Fields(PivotHelper.Month)) Then
e.DisplayText = _
CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(CInt(Fix(e.Value)))
End If
2013 DevExpress Inc.

1909

Products

1910

End Sub
Private Sub radioGroup1_SelectedIndexChanged(ByVal sender As Object, _
ByVal e As EventArgs) _
Handles radioGroup1.SelectedIndexChanged
Me.pivotGridControl1.LayoutChanged()
pivotGridControl1.BestFit()
End Sub
End Class
End Namespace

2013 DevExpress Inc.

1910

Products

1911

Data Editing
W inForms Controls > Products > Pivot Grid > Examples > Data Editing
This section contains the follow ing examples:
How to: Assign an In-place Editor to a Data Field's Cells
How to: Assign In-place Editors to Particular Cells
How to: Prevent Editors from Being Opened for Individual Cells

2013 DevExpress Inc.

1911

Products

1912

How to: Assign an In-place Editor to a Data Field's Cells


W inForms Controls > Products > Pivot Grid > Examples > Data Editing > How to: Assign an In-place Editor to a
Data Field's Cells
The follow ing example shows how to assign an in-place editor to cells of a specific data field, via the
PivotGridField.FieldEdit property. The assigned in-place editor (ProgressBar) controls the representation of cells in
display mode:

C#

C opy C ode

using DevExpress.XtraEditors.Repository;
RepositoryItemProgressBar riProgressBar = new RepositoryItemProgressBar();
pivotGridControl1.RepositoryItems.Add(riProgressBar);
fieldPercents.FieldEdit = riProgressBar;
Visual Basic

C opy C ode

Imports DevExpress.XtraEditors.Repository
Dim riProgressBar As RepositoryItemProgressBar = new RepositoryItemProgressBar()
pivotGridControl1.RepositoryItems.Add(riProgressBar)
fieldPercents.FieldEdit = riProgressBar

2013 DevExpress Inc.

1912

Products

1913

How to: Assign In-place Editors to Particular Cells


W inForms Controls > Products > Pivot Grid > Examples > Data Editing > How to: Assign In-place Editors to
Particular Cells
The follow ing code shows how to handle the PivotGridControl.CustomCellEdit event, to assign different in-place
editors to different types of cells.
In the example, tw o in-place editors (repository items) are created to represent values of the "Qty %" field. A
ProgressBar editor is used to represent regular cell values, while a SpinEdit editor is used to represent total
values for this field:

C#

C opy C ode

using DevExpress.XtraEditors.Repository;
using DevExpress.XtraPivotGrid;
// In-place editors used to represent values of regular and total cells respectively.
RepositoryItemProgressBar editorForCells;
RepositoryItemSpinEdit editorForTotals;
// Initialize the editors.
editorForCells = new RepositoryItemProgressBar();
editorForCells.Minimum = 0;
editorForCells.Maximum = 100;
editorForTotals = new RepositoryItemSpinEdit();
pivotGridControl1.RepositoryItems.AddRange(
new RepositoryItem[] { editorForCells, editorForTotals });
// Provide editors for cells depending on cell types
private void pivotGridControl1_CustomCellEdit(object sender, PivotCustomCellEditEventArgs e) {
if (e.DataField != fieldQuantityPercent) return;
if (e.RowValueType == PivotGridValueType.GrandTotal)
e.RepositoryItem = editorForTotals;
if (e.RowValueType == PivotGridValueType.Value)
e.RepositoryItem = editorForCells;
}
Visual Basic

C opy C ode

Imports DevExpress.XtraEditors.Repository
Imports DevExpress.XtraPivotGrid
' In-place editors used to represent values of regular and total cells respectively.
Dim editorForCells As RepositoryItemProgressBar
Dim editorForTotals As RepositoryItemSpinEdit
' Initialize the editors.
editorForCells = New RepositoryItemProgressBar()
editorForCells.Minimum = 0
editorForCells.Maximum = 100
editorForTotals = New RepositoryItemSpinEdit()
PivotGridControl1.RepositoryItems.AddRange(New RepositoryItem() _
{editorForCells, editorForTotals})
' Provide editors for cells depending on cell types
Private Sub PivotGridControl1_CustomCellEdit(ByVal sender As System.Object, _

2013 DevExpress Inc.

1913

Products

1914

ByVal e As PivotCustomCellEditEventArgs) Handles PivotGridControl1.CustomCellEdit


If e.DataField <> fieldQuantityPercent Then Return
If e.RowValueType = PivotGridValueType.GrandTotal Then e.RepositoryItem = editorForTotals
If e.RowValueType = PivotGridValueType.Value Then e.RepositoryItem = editorForCells
End Sub

2013 DevExpress Inc.

1914

Products

1915

How to: Prevent Editors from Being Opened for Individual Cells
W inForms Controls > Products > Pivot Grid > Examples > Data Editing > How to: Prevent Editors from Being
Opened for Individual Cells
The follow ing code shows how to disable data editing for total cells. This is accomplished by handling the
PivotGridControl.Show ingEditor event. When handling this event, the type of the current cell can be identified via
the PivotCellBaseEventArgs.ColumnValueType and PivotCellBaseEventArgs.Row ValueType parameters.
C#

C opy C ode

using DevExpress.XtraPivotGrid;
private void pivotGridControl1_ShowingEditor(object sender, CancelPivotCellEditEventArgs e) {
if (e.RowValueType != PivotGridValueType.Value || e.ColumnValueType != PivotGridValueType.Value)
e.Cancel = true;
}
Visual Basic

C opy C ode

Imports DevExpress.XtraPivotGrid
Private Sub PivotGridControl1_ShowingEditor(ByVal sender As System.Object, _
ByVal e As CancelPivotCellEditEventArgs) Handles PivotGridControl1.ShowingEditor
If e.RowValueType <> PivotGridValueType.Value OrElse e.ColumnValueType <> PivotGridValueType.Value
e.Cancel = True
End If
End Sub

2013 DevExpress Inc.

1915

Products

1916

Layout Features
W inForms Controls > Products > Pivot Grid > Examples > Layout Features
This section contains the follow ing examples:
How to: Group Fields
How to: Create User Folders w ithin the Customization Form
How to: Split Field Value Cells
How to: Display the Customization Form near the PivotGridControl
How to: Hide Individual Rows and Columns

2013 DevExpress Inc.

1916

Products

1917

How to: Group Fields


W inForms Controls > Products > Pivot Grid > Examples > Layout Features > How to: Group Fields
The follow ing example demonstrates how to combine fields into a group.
In the example three fields ('Country', 'Region' and 'City') are combined into a new group in this order. This
ensures that the 'Country' field will be followed by 'Region' which is in turn followed by 'City'. If the 'Region' field is
being dragged to another area the other fields will be dragged as well. The following image shows the 'Region'
field being dragged to the Filter Header Area.

C#

C opy C ode

using DevExpress.XtraPivotGrid;
PivotGridField fieldCountry = pivotGridControl1.Fields["Country"];
PivotGridField fieldRegion = pivotGridControl1.Fields["Region"];
PivotGridField fieldCity = pivotGridControl1.Fields["City"];
// Add a new group which combines the fields.
pivotGridControl1.Groups.Add(new PivotGridField[] {fieldCountry, fieldRegion, fieldCity});
Visual Basic

C opy C ode

Imports DevExpress.XtraPivotGrid
Dim fieldCountry As PivotGridField = PivotGridControl1.Fields("Country")
Dim fieldRegion As PivotGridField = PivotGridControl1.Fields("Region")
Dim fieldCity As PivotGridField = PivotGridControl1.Fields["City")
' Add a new group which combines the fields.
PivotGridControl1.Groups.Add(new PivotGridField() {fieldCountry, fieldRegion, fieldCity})

2013 DevExpress Inc.

1917

Products

1918

How to: Create User Folders within the Customization Form


W inForms Controls > Products > Pivot Grid > Examples > Layout Features > How to: Create User Folders w ithin
the Customization Form
Show Me
The complete sample project is available in the DevExpress Code Central database at http://w ww .devexpress.com/
example=E4391. Depending on the target platform type (ASP.NET, W inForms, etc), you can either run this example
online or dow nload an auto-executable sample.
The follow ing example shows how to group fields in the Customization Form by putting them in user-defined
folders.
In this example, the Customization Form is invoked by calling the PivotGridControl.FieldsCustomization method.
To enable displaying user folders, the PivotGridOptionsView Base.GroupFieldsInCustomizationW indow property is
set to true.
To create a folder for the Sales Person field, its PivotGridFieldBase.DisplayFolder property is set to "Employees".
To create the main folder and nested folders for Product Name and Category Name fields, their PivotGridFieldBase.
DisplayFolder properties are set to "Products\\Name" and "Products\\Category" respectively.
C#

C opy C ode

(Form1.cs)
using System;
using System.Drawing;
using System.Windows.Forms;
namespace XtraPivotGrid_UserFolders {
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e) {
// Binds the pivot grid to data.
this.salesPersonTableAdapter.Fill(this.nwindDataSet.SalesPerson);
// Enables displaying user folders.
pivotGridControl1.OptionsView.GroupFieldsInCustomizationWindow = true;
// Specifies the name of the folder in which the Employees field is located.
fieldSalesPerson.DisplayFolder = "Employees";
// Specifies names of the main folder and nested folders in which
// the Product Name and Category Name fields are located.
// Uses the "\" symbol as a delimiter when specifying folder names.
fieldProductName.DisplayFolder = "Products\\Name";
fieldCategoryName.DisplayFolder = "Products\\Category";
// Invokes the Customization Form at the lower right corner of the main window.
pivotGridControl1.FieldsCustomization();
}
}
}
Visual Basic

C opy C ode

(Form1.vb)
Imports Microsoft.VisualBasic
Imports System
Imports System.Drawing
Imports System.Windows.Forms
Namespace XtraPivotGrid_UserFolders
Partial Public Class Form1
Inherits Form
Public Sub New()
InitializeComponent()
End Sub
Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.Load
2013 DevExpress Inc.

1918

Products

1919

' Binds the pivot grid to data.


Me.salesPersonTableAdapter.Fill(Me.nwindDataSet.SalesPerson)
' Enables displaying user folders.
pivotGridControl1.OptionsView.GroupFieldsInCustomizationWindow = True
' Specifies the name of the folder in which the Employees field is located.
fieldSalesPerson.DisplayFolder = "Employees"
' Specifies names of the main folder and nested folders in which
' the Product Name and Category Name fields are located.
' Uses the "\" symbol as a delimiter when specifying folder names.
fieldProductName.DisplayFolder = "Products\Name"
fieldCategoryName.DisplayFolder = "Products\Category"
' Invokes the Customization Form at the lower right corner of the main window.
pivotGridControl1.FieldsCustomization()
End Sub
End Class
End Namespace

2013 DevExpress Inc.

1919

Products

1920

How to: Split Field Value Cells


W inForms Controls > Products > Pivot Grid > Examples > Layout Features > How to: Split Field Value Cells
Show Me
The complete sample project is available in the DevExpress Code Central database at http://w ww .devexpress.com/
example=E2763. Depending on the target platform type (ASP.NET, W inForms, etc), you can either run this example
online or dow nload an auto-executable sample.
The follow ing example demonstrates how to split field value cells.
In this example, the Grand Total column header is split into two cells: Price and Count. To do this, the
CustomFieldValueCells event is handled, and the event parameter's Split method is used. Cells that should be
split are identified by a predicate that returns true for those cells. The quantity, size and captions of newly created
cells are specified by an array of cell definitions (the FieldValueSplitData objects).
C#

C opy C ode

(Form1.cs)
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Windows.Forms;
using DevExpress.XtraPivotGrid;
using DevExpress.XtraPivotGrid.Data;
namespace XtraPivotGrid_SplittingCells {
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
pivotGridControl1.CustomFieldValueCells +=
new PivotCustomFieldValueCellsEventHandler(pivotGrid_CustomFieldValueCells);
}
void Form1_Load(object sender, EventArgs e) {
PivotHelper.FillPivot(pivotGridControl1);
pivotGridControl1.DataSource = PivotHelper.GetDataTable();
pivotGridControl1.BestFit();
}
protected void pivotGrid_CustomFieldValueCells(object sender,
PivotCustomFieldValueCellsEventArgs e) {
if (pivotGridControl1.DataSource == null) return;
if (radioGroup1.SelectedIndex == 0) return;
// Creates a predicate that returns true for the Grand Total
// headers, and false for any other column/row header.
// Only cells that match this predicate are split.
Predicate<FieldValueCell> condition =
new Predicate<FieldValueCell>(delegate(FieldValueCell matchCell) {
return matchCell.ValueType == PivotGridValueType.GrandTotal &&
matchCell.Field == null;
});
// Creates a list of cell definitions that represent newly created cells.
// Two definitions are added to the list. The first one identifies
// the Price cell, which has two nested cells (the Retail Price and Wholesale Price
// data field headers). The second one identifies the Count cell with
// one nested cell (the Quantity data field header).
List<FieldValueSplitData> cells = new List<FieldValueSplitData>(2);
cells.Add(new FieldValueSplitData("Price", 2));
cells.Add(new FieldValueSplitData("Count", 1));
// Performs splitting.
e.Split(true, condition, cells);
}
void pivotGridControl1_FieldValueDisplayText(object sender, PivotFieldDisplayTextEventArgs e) {
if(e.Field == pivotGridControl1.Fields[PivotHelper.Month]) {
e.DisplayText = CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName((int)e.Value);

2013 DevExpress Inc.

1920

Products

1921
}
}
void radioGroup1_SelectedIndexChanged(object sender, EventArgs e) {
this.pivotGridControl1.LayoutChanged();
pivotGridControl1.BestFit();
}

}
}
Visual Basic

C opy C ode

(Form1.vb)
Imports Microsoft.VisualBasic
Imports System
Imports System.Collections.Generic
Imports System.Globalization
Imports System.Windows.Forms
Imports DevExpress.XtraPivotGrid
Imports DevExpress.XtraPivotGrid.Data
Namespace XtraPivotGrid_SplittingCells
Partial Public Class Form1
Inherits Form
Public Sub New()
InitializeComponent()
AddHandler pivotGridControl1.CustomFieldValueCells, _
AddressOf pivotGrid_CustomFieldValueCells
End Sub
Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.Load
PivotHelper.FillPivot(pivotGridControl1)
pivotGridControl1.DataSource = PivotHelper.GetDataTable()
pivotGridControl1.BestFit()
End Sub
Protected Sub pivotGrid_CustomFieldValueCells(ByVal sender As Object, _
ByVal e As PivotCustomFieldValueCellsEventArgs)
If pivotGridControl1.DataSource Is Nothing Then
Return
End If
If radioGroup1.SelectedIndex = 0 Then
Return
End If
' Creates a predicate that returns true for the Grand Total
' headers, and false for any other column/row header.
' Only cells that match this predicate are split.
Dim condition As New Predicate(Of FieldValueCell)(AddressOf AnonymousMethod1)
' Creates a list of cell definitions that represent newly created cells.
' Two definitions are added to the list. The first one identifies
' the Price cell, which has two nested cells (the Retail Price and Wholesale Price
' data field headers). The second one identifies the Count cell with
' one nested cell (the Quantity data field header).
Dim cells As New List(Of FieldValueSplitData)(2)
cells.Add(New FieldValueSplitData("Price", 2))
cells.Add(New FieldValueSplitData("Count", 1))
' Performs splitting.
e.Split(True, condition, cells)
End Sub
Private Function AnonymousMethod1(ByVal matchCell As FieldValueCell) As Boolean
Return matchCell.ValueType = PivotGridValueType.GrandTotal AndAlso _
matchCell.Field Is Nothing
End Function
Private Sub pivotGridControl1_FieldValueDisplayText(ByVal sender As Object, _
ByVal e As PivotFieldDisplayTextEventArgs) _
Handles pivotGridControl1.FieldValueDisplayText
2013 DevExpress Inc.

1921

Products

1922

If Object.Equals(e.Field, pivotGridControl1.Fields(PivotHelper.Month)) Then


e.DisplayText = _
CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(CInt(Fix(e.Value)))
End If
End Sub
Private Sub radioGroup1_SelectedIndexChanged(ByVal sender As Object, _
ByVal e As EventArgs) _
Handles radioGroup1.SelectedIndexChanged
Me.pivotGridControl1.LayoutChanged()
pivotGridControl1.BestFit()
End Sub
End Class
End Namespace

2013 DevExpress Inc.

1922

Products

1923

How to: Display the Customization Form near the PivotGridControl


W inForms Controls > Products > Pivot Grid > Examples > Layout Features > How to: Display the Customization
Form near the PivotGridControl
Show Me
The complete sample project is available in the DevExpress Code Central database at http://w ww .devexpress.com/
example=E4572. Depending on the target platform type (ASP.NET, W inForms, etc), you can either run this example
online or dow nload an auto-executable sample.
This example demonstrates how to display the Customization Form near the PivotGridControl.
In this example, the SplitContainerControl is used as a parent container for the PivotGridControl and
Customization Form. The PivotGridControl.Show ingCustomizationForm event is handled to change the default
behavior of the Customization Form. The CustomizationFormShowingEventArgs.ParentControl property is used to
set SplitContainerControl.Panel2 as an ow ner of the Customization Form. The Customization Form is docked to
the parent container using the CustomizationFormShow ingEventArgs.CustomizationForm property.
The style of the Customization Form is set using the PivotGridOptionsCustomization.CustomizationFormStyle
property. The PivotGridControl.FieldsCustomization method is used to invoke the Customization Form.
C#

C opy C ode

(Form1.cs)
using System;
using System.Windows.Forms;
namespace StandaloneCustForm {
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e) {
// Binds the pivot grid to data.
this.salesPersonTableAdapter.Fill(this.nwindDataSet.SalesPerson);
// Sets the style of the Customization Form and invokes it.
pivotGridControl1.OptionsCustomization.CustomizationFormStyle =
DevExpress.XtraPivotGrid.Customization.CustomizationFormStyle.Excel2007;
pivotGridControl1.FieldsCustomization();
}
private void pivotGridControl1_ShowingCustomizationForm(object sender,
DevExpress.XtraPivotGrid.CustomizationFormShowingEventArgs e) {
// Sets the control which will own the Customization Form.
e.ParentControl = splitContainerControl1.Panel2;
// Sets the dock style applied to the Customization Form.
e.CustomizationForm.Dock = DockStyle.Fill;
}
}
}
Visual Basic

C opy C ode

(Form1.vb)
Imports Microsoft.VisualBasic
Imports System
Imports System.Windows.Forms
Namespace StandaloneCustForm
Partial Public Class Form1
Inherits Form
Public Sub New()
InitializeComponent()
End Sub
Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.Load
' Binds the pivot grid to data.
Me.salesPersonTableAdapter.Fill(Me.nwindDataSet.SalesPerson)

2013 DevExpress Inc.

1923

Products

1924

' Sets the style of the Customization Form and invokes it.
pivotGridControl1.OptionsCustomization.CustomizationFormStyle = DevExpress.XtraPivotGrid. _
Customization.CustomizationFormStyle.Excel2007
pivotGridControl1.FieldsCustomization()
End Sub
Private Sub pivotGridControl1_ShowingCustomizationForm( _
ByVal sender As Object, ByVal e As DevExpress.XtraPivotGrid.CustomizationFormShowingEventArgs) _
Handles pivotGridControl1.ShowingCustomizationForm
' Sets the control which will own the Customization Form.
e.ParentControl = splitContainerControl1.Panel2
' Sets the dock style applied to the Customization Form.
e.CustomizationForm.Dock = DockStyle.Fill
End Sub
End Class
End Namespace

2013 DevExpress Inc.

1924

Products

1925

How to: Hide Individual Rows and Columns


W inForms Controls > Products > Pivot Grid > Examples > Layout Features > How to: Hide Individual Row s and
Columns
Show Me
The complete sample project is available in the DevExpress Code Central database at http://w ww .devexpress.com/
example=E2769. Depending on the target platform type (ASP.NET, W inForms, etc), you can either run this example
online or dow nload an auto-executable sample.
The follow ing example demonstrates how to hide particular row s and columns by handling the
CustomFieldValueCells event.
In this example, the event handler iterates through all row headers and removes rows that correspond to the
"Employee B" field value, and that are not Total Rows.
C#

C opy C ode

(Form1.cs)
using System;
using System.Globalization;
using System.Windows.Forms;
using DevExpress.XtraPivotGrid;
namespace XtraPivotGrid_HidingColumnsAndRows {
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
pivotGridControl1.CustomFieldValueCells +=
new PivotCustomFieldValueCellsEventHandler(pivotGrid_CustomFieldValueCells);
}
void Form1_Load(object sender, EventArgs e) {
PivotHelper.FillPivot(pivotGridControl1);
pivotGridControl1.DataSource = PivotHelper.GetDataTable();
pivotGridControl1.BestFit();
}
// Handles the CustomFieldValueCells event to remove
// specific rows.
protected void pivotGrid_CustomFieldValueCells(object sender,
PivotCustomFieldValueCellsEventArgs e) {
if (pivotGridControl1.DataSource == null) return;
if (radioGroup1.SelectedIndex == 0) return;
// Iterates through all row headers.
for (int i = e.GetCellCount(false) - 1; i >= 0; i--) {
FieldValueCell cell = e.GetCell(false, i);
if (cell == null) continue;
// If the current header corresponds to the "Employee B"
// field value, and is not the Total Row header,
// it is removed with all corresponding rows.
if (object.Equals(cell.Value, "Employee B") &&
cell.ValueType != PivotGridValueType.Total)
e.Remove(cell);
}
}
void pivotGridControl1_FieldValueDisplayText(object sender,
PivotFieldDisplayTextEventArgs e) {
if(e.Field == pivotGridControl1.Fields[PivotHelper.Month]) {
e.DisplayText = CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName((int)e.Value);
}
}
void radioGroup1_SelectedIndexChanged(object sender, EventArgs e) {
this.pivotGridControl1.LayoutChanged();
pivotGridControl1.BestFit();
}

2013 DevExpress Inc.

1925

Products

1926

}
}
Visual Basic

C opy C ode

(Form1.vb)
Imports Microsoft.VisualBasic
Imports System
Imports System.Globalization
Imports System.Windows.Forms
Imports DevExpress.XtraPivotGrid
Namespace XtraPivotGrid_HidingColumnsAndRows
Partial Public Class Form1
Inherits Form
Public Sub New()
InitializeComponent()
AddHandler pivotGridControl1.CustomFieldValueCells, _
AddressOf pivotGrid_CustomFieldValueCells
End Sub
Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.Load
PivotHelper.FillPivot(pivotGridControl1)
pivotGridControl1.DataSource = PivotHelper.GetDataTable()
pivotGridControl1.BestFit()
End Sub
' Handles the CustomFieldValueCells event to remove
' specific rows.
Protected Sub pivotGrid_CustomFieldValueCells(ByVal sender As Object, _
ByVal e As PivotCustomFieldValueCellsEventArgs)
If pivotGridControl1.DataSource Is Nothing Then
Return
End If
If radioGroup1.SelectedIndex = 0 Then
Return
End If
' Iterates through all row headers.
For i As Integer = e.GetCellCount(False) - 1 To 0 Step -1
Dim cell As FieldValueCell = e.GetCell(False, i)
If cell Is Nothing Then Continue For
' If the current header corresponds to the "Employee B"
' field value, and is not the Total Row header,
' it is removed with all corresponding rows.
If Object.Equals(cell.Value, "Employee B") AndAlso _
cell.ValueType <> PivotGridValueType.Total Then
e.Remove(cell)
End If
Next i
End Sub
Private Sub pivotGridControl1_FieldValueDisplayText(ByVal sender As Object, _
ByVal e As PivotFieldDisplayTextEventArgs) _
Handles pivotGridControl1.FieldValueDisplayText
If Object.Equals(e.Field, pivotGridControl1.Fields(PivotHelper.Month)) Then
e.DisplayText = _
CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(CInt(Fix(e.Value)))
End If
End Sub
Private Sub radioGroup1_SelectedIndexChanged(ByVal sender As Object, _
ByVal e As EventArgs) _
Handles radioGroup1.SelectedIndexChanged
Me.pivotGridControl1.LayoutChanged()
pivotGridControl1.BestFit()
End Sub
End Class
2013 DevExpress Inc.

1926

Products

1927

End Namespace

2013 DevExpress Inc.

1927

Products

1928

Data Formatting
W inForms Controls > Products > Pivot Grid > Examples > Data Formatting
This section contains the follow ing examples:
How to: Format Cell Values

2013 DevExpress Inc.

1928

Products

1929

How to: Format Cell Values


W inForms Controls > Products > Pivot Grid > Examples > Data Formatting > How to: Format Cell Values
The follow ing example shows how to format data that corresponds to a 'Quantity' and 'Extended Price' data fields
in a sample XtraPivotGrid control.
For the 'Quantity' field the PivotGridFieldBase.CellFormat property is used to format data in a custom manner. The
values that correspond to this field are enclosed w ith round brackets. The formatting settings specified by the
PivotGridFieldBase.CellFormat property also affect the representation of total and grand total cells
The 'Extended Price' field is bound to a field that contains currency data. By default the cell values that correspond
to such fields are formatted as currency amounts (the formatting settings are determined by the regional
settings). For English (United States) culture the currency values are represented using two digits to the right of
the decimal point. In the example, the PivotGridFieldBase.GrandTotalCellFormat property is used to format grand
total cell values for the 'Extended Price' field in a different manner. The data in these cells is formatted as integer
currency values (w ithout fractional portions).
The result of the code is shown below:

C#

C opy C ode

// Formatting settings for the 'Quantity' field.


fieldQuantity.CellFormat.FormatType = DevExpress.Utils.FormatType.Custom;
fieldQuantity.CellFormat.FormatString = "({0})";
// Formatting settings for the 'Extended Price' field.
fieldExtendedPrice.GrandTotalCellFormat.FormatType = DevExpress.Utils.FormatType.Numeric;
fieldExtendedPrice.GrandTotalCellFormat.FormatString = "c0";
Visual Basic

C opy C ode

' Formatting settings for the 'Quantity' field.


FieldQuantity.CellFormat.FormatType = DevExpress.Utils.FormatType.Custom
FieldQuantity.CellFormat.FormatString = "({0})"
' Formatting settings for the 'Extended Price' field.
FieldExtendedPrice.GrandTotalCellFormat.FormatType = DevExpress.Utils.FormatType.Numeric
FieldExtendedPrice.GrandTotalCellFormat.FormatString = "c0"

2013 DevExpress Inc.

1929

Products

1930

Data Output
W inForms Controls > Products > Pivot Grid > Examples > Data Output
This section contains the follow ing examples:
How to: Visualize Pivot Grid Data via the XtraCharts Suite
How to: Customize PivotGridControl Data before Displaying It in a Chart Control
How to: Export Data
How to: Print a PivotGrid and Show its Print Preview
How to: Copy Data to the Clipboard

2013 DevExpress Inc.

1930

Products

1931

How to: Visualize Pivot Grid Data via the XtraCharts Suite
W inForms Controls > Products > Pivot Grid > Examples > Data Output > How to: Visualize Pivot Grid Data via the
XtraCharts Suite
Show Me
The complete sample project is available in the DevExpress Code Central database at http://w ww .devexpress.com/
example=E2911. Depending on the target platform type (ASP.NET, W inForms, etc), you can either run this example
online or dow nload an auto-executable sample.
The follow ing example shows how to bind a ChartControl to a PivotGridControl to visualize data.
In this example, after a PivotGridControl and ChartControl are created, the PivotGridControl instance is assigned
to the ChartControl.DataSource property. By default, the ChartControl.AutoBindingSettingsEnabled property is set
to true, so that binding settings are automatically adjusted, and no further customization is needed. Once the
ChartControl is bound to the PivotGridControl, PivotGridControl data is immediately displayed in the chart.
The main form of this sample application contains the 'Transpose Data Source' check box that defines the pivot
grid's PivotGridOptionsChartDataSourceBase.ProvideDataByColumns property value. If the check box is checked,
the property is set to false, and series are created based on pivot grid row s (instead of columns, w hich is the
default behavior).
C#

C opy C ode

(Form1.cs)
using System;
using System.Windows.Forms;
namespace XtraPivotGrid_ChartsIntegration {
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e) {
// Populates the pivot grid's data source with data.
this.salesPersonTableAdapter.Fill(this.nwindDataSet.SalesPerson);
// Sets the PivotGridControl as a data source for the ChartControl.
chartControl1.DataSource = pivotGridControl1;
}
}
}
Visual Basic

C opy C ode

(Form1.vb)
Imports Microsoft.VisualBasic
Imports System
Imports System.Windows.Forms
Namespace XtraPivotGrid_ChartsIntegration
Partial Public Class Form1
Inherits Form
Public Sub New()
InitializeComponent()
End Sub
Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.Load
' Populates the pivot grid's data source with data.
Me.salesPersonTableAdapter.Fill(Me.nwindDataSet.SalesPerson)
' Sets the PivotGridControl as a data source for the ChartControl.
chartControl1.DataSource = pivotGridControl1
End Sub
End Class
End Namespace

2013 DevExpress Inc.

1931

Products

1932

How to: Customize PivotGridControl Data before Displaying It in a Chart Contr


W inForms Controls > Products > Pivot Grid > Examples > Data Output > How to: Customize PivotGridControl Data
before Displaying It in a Chart Control
Show Me
The complete sample project is available in the DevExpress Code Central database at http://w ww .devexpress.com/
example=E2214. Depending on the target platform type (ASP.NET, W inForms, etc), you can either run this example
online or dow nload an auto-executable sample.
The follow ing example demonstrates how to add custom text to data prepared by the PivotGridControl, to display
it in a ChartControl.
For this, it is necessary to handle the PivotGridControl.CustomChartDataSourceData event. In this event handler,
you can determine the item type via the PivotCustomChartDataSourceDataEventArgs.ItemType property and
change the PivotCustomChartDataSourceDataEventArgs.Value according to your custom requirements.
C#

C opy C ode

(Form1.cs)
private void pivotGridControl1_CustomChartDataSourceData(object sender,
PivotCustomChartDataSourceDataEventArgs e) {
if(e.ItemType == PivotChartItemType.RowItem) {
if(e.FieldValueInfo.Field == fieldCategoryName) {
e.Value = CategoryEncodeTable[e.FieldValueInfo.Value.ToString()];
} else if(e.FieldValueInfo.Field == fieldProductName) {
string product =
ProductEncodeTable[e.FieldValueInfo.Value.ToString()];
string category =
CategoryEncodeTable[e.FieldValueInfo.GetHigherLevelFieldValue(fieldCategoryName).ToString()
e.Value = product + '[' + category + ']';
}
}
if(e.ItemType == PivotChartItemType.ColumnItem) {
if(e.FieldValueInfo.ValueType == PivotGridValueType.GrandTotal) {
e.Value = "Total Sales";
}
}
if(e.ItemType == PivotChartItemType.CellItem) {
e.Value = Math.Round(Convert.ToDecimal(e.CellInfo.Value), 0);
}
}
Visual Basic

C opy C ode

(Form1.vb)
Private Sub pivotGridControl1_CustomChartDataSourceData(ByVal sender As Object, _
ByVal e As PivotCustomChartDataSourceDataEventArgs) _
Handles pivotGridControl1.CustomChartDataSourceData
If e.ItemType = PivotChartItemType.RowItem Then
If Object.Equals(e.FieldValueInfo.Field, fieldCategoryName) Then
e.Value = CategoryEncodeTable(e.FieldValueInfo.Value.ToString())
ElseIf Object.Equals(e.FieldValueInfo.Field, fieldProductName) Then
Dim product As String = _
ProductEncodeTable(e.FieldValueInfo.Value.ToString())
Dim category As String = _
CategoryEncodeTable(e.FieldValueInfo.GetHigherLevelFieldValue(fieldCategoryName).ToStri
e.Value = product & "["c & category & "]"c
End If
End If
If e.ItemType = PivotChartItemType.ColumnItem Then
If e.FieldValueInfo.ValueType = PivotGridValueType.GrandTotal Then
e.Value = "Total Sales"
End If
2013 DevExpress Inc.

1932

Products

1933

End If
If e.ItemType = PivotChartItemType.CellItem Then
e.Value = Math.Round(Convert.ToDecimal(e.CellInfo.Value), 0)
End If
End Sub

2013 DevExpress Inc.

1933

Products

1934

How to: Export Data


W inForms Controls > Products > Pivot Grid > Examples > Data Output > How to: Export Data
The follow ing example shows how to export the PivotGridControl's data to a file in XLS format:
C#

C opy C ode

pivotGridControl1.ExportToXls("c:\\pivotGrid_output.xls");
Visual Basic

C opy C ode

PivotGridControl1.ExportToXls("c:\pivotGrid output.xls")

2013 DevExpress Inc.

1934

Products

1935

How to: Print a PivotGrid and Show its Print Preview


W inForms Controls > Products > Pivot Grid > Examples > Data Output > How to: Print a PivotGrid and Show its
Print Preview
The follow ing example demonstrates how to print a PivotGridControl or show its Print Preivew . To do this, you
should use either the PivotGridControl.Print or PivotGridControl.ShowPrintPreview methods.
Note
The PivotGridControl can be printed and previewed only if the XtraPrinting Library is available. To verify that printing
the PivotGridControl is possible, use the PivotGridControl.IsPrintingAvailable property.
W hen printing a PivotGridControl, the current print settings will be used to represent a PivotGridControl. Note that
you can access and change these settings via the PivotGridControl.OptionsPrint property.
C#

C opy C ode

using DevExpress.XtraPivotGrid;
// ...
private void ShowPivotGridPreview(PivotGridControl pivotGrid) {
// Check whether the PivotGridControl can be previewed.
if (!pivotGrid.IsPrintingAvailable) {
MessageBox.Show("The 'DevExpress.XtraPrinting.v7.2.dll' is not found", "Error");
return;
}
// Open the Preview window.
pivotGrid.ShowPrintPreview();
}
private void PrintPivotGrid(PivotGridControl pivotGrid) {
// Check whether the PivotGridControl can be printed.
if (!pivotGrid.IsPrintingAvailable) {
MessageBox.Show("The 'DevExpress.XtraPrinting.v7.2.dll' is not found", "Error");
return;
}
// Print.
pivotGrid.Print();
}
Visual Basic

C opy C ode

Imports DevExpress.XtraPivotGrid
' ...
Sub ShowPivotGridPreview(ByVal pivotGrid As PivotGridControl)
' Check whether the PivotGridControl can be previewed.
If Not pivotGrid.IsPrintingAvailable Then
MessageBox.Show("The 'DevExpress.XtraPrinting.v7.2.dll' is not found", "Error")
Return
End If
' Opens the Preview window.
pivotGrid.ShowPrintPreview()
End Sub
Sub PrintPivotGrid(ByVal pivotGrid As PivotGridControl)
' Check whether the PivotGridControl can be printed.
If Not pivotGrid.IsPrintingAvailable Then
MessageBox.Show("The 'DevExpress.XtraPrinting.v7.2.dll' is not found", "Error")
Return
End If
' Print.
pivotGrid.Print()
End Sub
The image below show s the result.

2013 DevExpress Inc.

1935

Products

2013 DevExpress Inc.

1936

1936

Products

1937

How to: Copy Data to the Clipboard


W inForms Controls > Products > Pivot Grid > Examples > Data Output > How to: Copy Data to the Clipboard
Assume that the PopupMenu component has already been placed on a form. It has a single menu item - "Copy to
Clipboard". This context menu is invoked w hen an end-user right-clicks within the Data Area. The item's ItemClick
event is handled to copy data to the clipboard. To copy the selected cells to the clipboard the PivotGridCells.
CopySelectionToClipboard method is used.
To determine w hether an end-user has right-clicked within the Data Area, the PivotGridControl.CalcHitInfo method
is used. It returns the PivotGridHitInfo object w hose PivotGridHitInfo.HitTest property identifies whether the cell
has been clicked.
The image below show s the result.

C#

C opy C ode

using DevExpress.XtraPivotGrid;
// ...
private void pivotGridControl1_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e) {
Point pt = new Point(e.X, e.Y);
if(e.Button != MouseButtons.Right) return;
if(pivotGridControl1.CalcHitInfo(pt).HitTest != PivotGridHitTest.Cell) return;
// Shows the context menu.
popupMenu1.ShowPopup(barManager1, pivotGridControl1.PointToScreen(pt));
}
private void barButtonItem1_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e) {
pivotGridControl1.Cells.CopySelectionToClipboard();
}
Visual Basic

C opy C ode

Imports DevExpress.XtraPivotGrid
' ...
Private Sub PivotGridControl1_MouseUp(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEven
Dim pt As Point = New Point(e.X, e.Y)

2013 DevExpress Inc.

1937

Products

1938

If e.Button <> MouseButtons.Right Then


Exit Sub
End If
If PivotGridControl1.CalcHitInfo(pt).HitTest <> PivotGridHitTest.Cell Then
Exit Sub
End If
' Shows the context menu.
PopupMenu1.ShowPopup(BarManager1, PivotGridControl1.PointToScreen(pt))
End Sub
Private Sub BarButtonItem1_ItemClick(ByVal sender As Object, ByVal e As DevExpress.XtraBars.ItemClickEv
PivotGridControl1.Cells.CopySelectionToClipboard()
End Sub

2013 DevExpress Inc.

1938

Products

1939

Appearance
W inForms Controls > Products > Pivot Grid > Examples > Appearance
This section contains the follow ing examples:
How to: Customize Appearances of Cells via an Event
How to: Apply Conditional Formatting to Data Cells
How to: Custom Paint Cells

2013 DevExpress Inc.

1939

Products

1940

How to: Customize Appearances of Cells via an Event


W inForms Controls > Products > Pivot Grid > Examples > Appearance > How to: Customize Appearances of Cells
via an Event
The follow ing example shows how to customize the appearance of specific cells via the PivotGridControl.
CustomAppearance event.
In this example, custom appearance settings (the yellow background and bold font) are applied to a cell if it meets
the following conditions:
It belongs to an "ExtendedPrice" data field.
It's not displayed within total rows or columns.
It's value is larger than 1000.
The follow ing image demonstrates code execution:

C#

C opy C ode

using DevExpress.XtraPivotGrid;
private void pivotGridControl1_CustomAppearance(object sender, PivotCustomAppearanceEventArgs e) {
if (e.DataField == fieldExtendedPrice && e.ColumnValueType == PivotGridValueType.Value
&& e.RowValueType == PivotGridValueType.Value) {
if (e.Value != null && (decimal)e.Value > 1000) {
e.Appearance.BackColor = Color.Yellow;
e.Appearance.Font = new Font(e.Appearance.Font, FontStyle.Bold);
}
}
}
Visual Basic

C opy C ode

Imports DevExpress.XtraPivotGrid
Private Sub pivotGridControl1_CustomAppearance(ByVal sender As System.Object, _
ByVal e As PivotCustomAppearanceEventArgs) _
Handles pivotGridControl1.CustomAppearance
If e.DataField Is fieldExtendedPrice And e.ColumnValueType = PivotGridValueType.Value _
And e.RowValueType = PivotGridValueType.Value Then
If Not e.Value Is Nothing And Convert.ToDecimal(e.Value) > 1000 Then
e.Appearance.BackColor = Color.Yellow
e.Appearance.Font = New Font(e.Appearance.Font, FontStyle.Bold)
End If
End If
End Sub

2013 DevExpress Inc.

1940

Products

1941

How to: Apply Conditional Formatting to Data Cells


W inForms Controls > Products > Pivot Grid > Examples > Appearance > How to: Apply Conditional Formatting to
Data Cells
The follow ing sample applies conditional formatting to the data cells of a PivotGridControl. The cells whose values
are less than 10000 are painted w ith custom appearance settings. For this purpose a new
PivotGridStyleFormatCondition object w hich represents a style format condition is created, customized and added
to the PivotGridControl's PivotGridControl.FormatConditions collection.
The image below show s the result.

C#

C opy C ode

using DevExpress.XtraPivotGrid;
// Creating and customizing a new style format condition.
PivotGridStyleFormatCondition fCondition = new PivotGridStyleFormatCondition();
fCondition.Field = fieldExtendedPrice;
fCondition.ApplyToCustomTotalCell = false;
fCondition.ApplyToGrandTotalCell = false;
fCondition.ApplyToTotalCell = false;
fCondition.Condition = DevExpress.XtraGrid.FormatConditionEnum.Less;
fCondition.Value1 = 10000;
fCondition.Appearance.BackColor = Color.Yellow;
fCondition.Appearance.Font = new Font(fCondition.Appearance.Font, FontStyle.Bold);
fCondition.Appearance.Options.UseBackColor = true;
fCondition.Appearance.Options.UseFont = true;
// Adds the format condition to the collection.
pivotGridControl1.FormatConditions.Add(fCondition);
Visual Basic

C opy C ode

Imports DevExpress.XtraPivotGrid
' Creating and customizing a new style format condition.
Dim fCondition As PivotGridStyleFormatCondition = New PivotGridStyleFormatCondition()
fCondition.Field = FieldExtendedPrice
fCondition.ApplyToCustomTotalCell = False
fCondition.ApplyToGrandTotalCell = False
fCondition.ApplyToTotalCell = False
fCondition.Condition = DevExpress.XtraGrid.FormatConditionEnum.Less
fCondition.Value1 = 10000
fCondition.Appearance.BackColor = Color.Yellow
fCondition.Appearance.Font = New Font(fCondition.Appearance.Font, FontStyle.Bold)
fCondition.Appearance.Options.UseBackColor = True
fCondition.Appearance.Options.UseFont = True
' Adds the format condition to the collection.
PivotGridControl1.FormatConditions.Add(fCondition)

2013 DevExpress Inc.

1941

Products

1942

How to: Custom Paint Cells


W inForms Controls > Products > Pivot Grid > Examples > Appearance > How to: Custom Paint Cells
The follow ing example shows how to custom paint cells (normal, focused, selected and Grand Total cells) w ithin
the PivotGridControl's Data Area. For this purpose the PivotGridControl.CustomDraw Cell event is handled. The
event parameter's properties allow the processed cell to be identified.
The image below show s the result.

C#

C opy C ode

using System.Drawing.Drawing2D;
using DevExpress.XtraPivotGrid;
// ...
private void pivotGridControl1_CustomDrawCell(object sender, PivotCustomDrawCellEventArgs e) {
Rectangle r;
// Paints Row Grand Totals.
if(e.RowValueType == PivotGridValueType.GrandTotal) {
e.GraphicsCache.FillRectangle(new LinearGradientBrush(e.Bounds, Color.LightBlue,
Color.Blue, LinearGradientMode.Vertical), e.Bounds);
r = Rectangle.Inflate(e.Bounds, -3, -3);
e.GraphicsCache.FillRectangle(new LinearGradientBrush(e.Bounds, Color.Blue,
Color.LightSkyBlue, LinearGradientMode.Vertical), r);
e.GraphicsCache.DrawString(e.DisplayText, e.Appearance.Font,
new SolidBrush(Color.White), r, e.Appearance.GetStringFormat());
e.Handled = true;
return;
}
// Paints the data cells.
Brush backBrush;
r = e.Bounds;
if (e.Focused)
// Initializes the brush used to paint the focused cell.
backBrush = e.GraphicsCache.GetSolidBrush(Color.OrangeRed);
else
if(e.Selected)
// Initializes the brush used to paint selected cells.
backBrush = e.GraphicsCache.GetSolidBrush(Color.Blue);
else
// Initializes the brush used to paint data cells.
backBrush = e.GraphicsCache.GetSolidBrush(Color.Yellow);
e.GraphicsCache.DrawRectangle(new Pen(new SolidBrush(Color.Black), 1), r);

2013 DevExpress Inc.

1942

Products

1943

r.Inflate(-1, -1);
e.GraphicsCache.FillRectangle(backBrush, r);
e.Appearance.DrawString(e.GraphicsCache, e.DisplayText, r);
e.Handled = true;
}
Visual Basic

C opy C ode

Imports System.Drawing.Drawing2D
Imports DevExpress.XtraPivotGrid
' ...
Private Sub PivotGridControl1_CustomDrawCell(ByVal sender As Object, ByVal e As _
PivotCustomDrawCellEventArgs) Handles PivotGridControl1.CustomDrawCell
Dim r As Rectangle
' Paints Row Grand Totals.
If e.RowValueType = PivotGridValueType.GrandTotal Then
e.GraphicsCache.FillRectangle(New LinearGradientBrush(e.Bounds, Color.LightBlue, _
Color.Blue, LinearGradientMode.Vertical), e.Bounds)
r = Rectangle.Inflate(e.Bounds, -3, -3)
e.GraphicsCache.FillRectangle(New LinearGradientBrush(e.Bounds, Color.Blue, _
Color.LightSkyBlue, LinearGradientMode.Vertical), r)
e.GraphicsCache.DrawString(e.DisplayText, e.Appearance.Font, New SolidBrush(Color.White), _
r, e.Appearance.GetStringFormat())
e.Handled = True
Exit Sub
End If
' Paints the data cells.
Dim backBrush As Brush
r = e.Bounds
If e.Focused Then
' Initializes the brush used to paint the focused cell.
backBrush = e.GraphicsCache.GetSolidBrush(Color.OrangeRed)
ElseIf e.Selected Then
' Initializes the brush used to paint selected cells.
backBrush = e.GraphicsCache.GetSolidBrush(Color.Blue)
Else
' Initializes the brush used to paint data cells.
backBrush = e.GraphicsCache.GetSolidBrush(Color.Yellow)
End If
e.GraphicsCache.DrawRectangle(New Pen(New SolidBrush(Color.Black), 1), r)
r.Inflate(-1, -1)
e.GraphicsCache.FillRectangle(backBrush, r)
e.Appearance.DrawString(e.GraphicsCache, e.DisplayText, r)
e.Handled = True
End Sub

2013 DevExpress Inc.

1943

Products

1944

Miscellaneous
W inForms Controls > Products > Pivot Grid > Examples > Miscellaneous
This section contains the follow ing examples:
How to: Save and Restore Layout
How to: Save and Load Field Values' Collapsed States Together W ith Pivot Grid Layout
How to: Implement a Custom Serializer

2013 DevExpress Inc.

1944

Products

1945

How to: Save and Restore Layout


W inForms Controls > Products > Pivot Grid > Examples > Miscellaneous > How to: Save and Restore Layout
The follow ing sample code saves a PivotGridControl's layout to a memory stream and then restores it.
C#

C opy C ode

System.IO.Stream stream;
stream = new System.IO.MemoryStream();
pivotGridControl1.SaveLayoutToStream(stream);
stream.Seek(0, System.IO.SeekOrigin.Begin);
// ...
pivotGridControl1.RestoreLayoutFromStream(stream);
stream.Seek(0, System.IO.SeekOrigin.Begin);
Visual Basic

C opy C ode

Dim stream As System.IO.Stream


stream = New System.IO.MemoryStream()
PivotGridControl1.SaveLayoutToStream(stream)
stream.Seek(0, System.IO.SeekOrigin.Begin)
' ...
PivotGridControl1.RestoreLayoutFromStream(stream)
stream.Seek(0, System.IO.SeekOrigin.Begin)

2013 DevExpress Inc.

1945

Products

1946

How to: Save and Load Field Values' Collapsed States Together With Pivot Gr
W inForms Controls > Products > Pivot Grid > Examples > Miscellaneous > How to: Save and Load Field Values'
Collapsed States Together With Pivot Grid Layout
Show Me
The complete sample project is available in the DevExpress Code Central database at http://w ww .devexpress.com/
example=E20014. Depending on the target platform type (ASP.NET, W inForms, etc), you can either run this example
online or dow nload an auto-executable sample.
Field values' collapsed states can be restored only in the same layout they have been saved in. This example
shows how to save and load a control's layout together with collapsed states to ensure that the states are
loaded in the appropriate layout.
This example displays a pivot grid control and three buttons: Save, Load and Clear. When the Save button is
clicked, the control layout and field values' collapsed states are saved to streams via the SaveLayoutToStream
and SaveCollapsedStateToStream methods, respectively. On the Load button click, the RestoreLayoutFromStream
method is firstly called to restore the layout, and then the collapsed states are loaded using the
LoadCollapsedStateFromStream method. This ensures that even if you remove all fields from the pivot grid via the
Clear button, the control's state w ill be restored w hen you click the Load button.
C#

C opy C ode

(Form1.cs)
using System;
using System.IO;
using System.Windows.Forms;
using DevExpress.Utils;
namespace XtraPivotGrid_SaveLoadCollapsedState {
public partial class Form1 : Form {
MemoryStream layoutStream = new MemoryStream();
MemoryStream collapseStateStream = new MemoryStream();
public Form1() {
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e) {
nwindDataSetTableAdapters.ProductReportsTableAdapter adapter =
new nwindDataSetTableAdapters.ProductReportsTableAdapter();
pivotGridControl1.DataSource = adapter.GetData();
}
private void btnSave_Click(object sender, EventArgs e) {
layoutStream.Dispose();
layoutStream = new MemoryStream();
pivotGridControl1.SaveLayoutToStream(layoutStream, OptionsLayoutBase.FullLayout);
collapseStateStream.Dispose();
collapseStateStream = new MemoryStream();
pivotGridControl1.SaveCollapsedStateToStream(collapseStateStream);
}
private void btnLoad_Click(object sender, EventArgs e) {
layoutStream.Seek(0, SeekOrigin.Begin);
pivotGridControl1.RestoreLayoutFromStream(layoutStream, OptionsLayoutBase.FullLayout);
collapseStateStream.Seek(0, SeekOrigin.Begin);
pivotGridControl1.LoadCollapsedStateFromStream(collapseStateStream);
}
private void btnClear_Click(object sender, EventArgs e) {
pivotGridControl1.Fields.Clear();
}
}
}
Visual Basic

C opy C ode

(Form1.vb)
Imports Microsoft.VisualBasic

2013 DevExpress Inc.

1946

Products

1947

Imports System
Imports System.IO
Imports System.Windows.Forms
Imports DevExpress.Utils
Namespace XtraPivotGrid_SaveLoadCollapsedState
Partial Public Class Form1
Inherits Form
Private layoutStream As New MemoryStream()
Private collapseStateStream As New MemoryStream()
Public Sub New()
InitializeComponent()
End Sub
Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.Load
Dim adapter As New nwindDataSetTableAdapters.ProductReportsTableAdapter()
pivotGridControl1.DataSource = adapter.GetData()
End Sub
Private Sub btnSave_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnSave.Click
layoutStream.Dispose()
layoutStream = New MemoryStream()
pivotGridControl1.SaveLayoutToStream(layoutStream, OptionsLayoutBase.FullLayout)
collapseStateStream.Dispose()
collapseStateStream = New MemoryStream()
pivotGridControl1.SaveCollapsedStateToStream(collapseStateStream)
End Sub
Private Sub btnLoad_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnLoad.Click
layoutStream.Seek(0, SeekOrigin.Begin)
pivotGridControl1.RestoreLayoutFromStream(layoutStream, OptionsLayoutBase.FullLayout)
collapseStateStream.Seek(0, SeekOrigin.Begin)
pivotGridControl1.LoadCollapsedStateFromStream(collapseStateStream)
End Sub
Private Sub btnClear_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnClear.Click
pivotGridControl1.Fields.Clear()
End Sub
End Class
End Namespace

2013 DevExpress Inc.

1947

Products

1948

How to: Implement a Custom Serializer


W inForms Controls > Products > Pivot Grid > Examples > Miscellaneous > How to: Implement a Custom Serializer
Show Me
The complete sample project is available in the DevExpress Code Central database at http://w ww .devexpress.com/
example=E2879. Depending on the target platform type (ASP.NET, W inForms, etc), you can either run this example
online or dow nload an auto-executable sample.
The follow ing example shows how to implement a custom serializer.
Custom serializers are required when data source field values are custom objects (not numeric or string values).
In this example, the data source contains a Sales Person field w hose values are Employee objects, exposing the
FirstName, LastName and Age properties. The Employee class implements the IComparable interface, and
overrides the GetHashCode, Equals and ToString methods (required to display and handle custom objects).
The custom serializer is represented by the CustomObjectConverter class, which implements the
ICustomObjectConverter interface. The ToString and FromString methods are implemented to serialize and
deserialize the Employee objects, respectively. A CustomObjectConverter class instance is assigned to the
PivotGridOptionsData.CustomObjectConverter property. It is used for serializing Sales Person field values w hen
pivot grid data is saved to a stream and restored back by an end-user via clicking the Save and Load buttons
respectively.
C#

C opy C ode

(Form1.cs)
using System;
using System.IO;
using System.Windows.Forms;
using DevExpress.Data.PivotGrid;
using DevExpress.Utils.Serializing.Helpers;
namespace XtraPivotGrid_CustomObjectConverter {
public partial class Form1 : Form {
MemoryStream stream;
public Form1() {
InitializeComponent();
pivotGridControl1.DataSource = DataHelper.GetData();
pivotGridControl1.OptionsData.CustomObjectConverter = new CustomObjectConverter();
}
// Handles the Save button's Click event to save pivot grid data to a stream
// (requires data source serialization).
private void simpleButton1_Click(object sender, EventArgs e) {
if (stream != null) stream.Dispose();
stream = new MemoryStream();
pivotGridControl1.SavePivotGridToStream(stream);
}
// Handles the Load button's Click event to load pivot grid data from a stream
// (requires stream content deserialization).
private void simpleButton2_Click(object sender, EventArgs e) {
if (stream == null) return;
PivotFileDataSource ds = new PivotFileDataSource(stream, new CustomObjectConverter());
pivotGridControl1.DataSource = ds;
}
}
// Implements a custom serializer.
public class CustomObjectConverter : ICustomObjectConverter {
// Returns a value, indicatingwhether objects of the specified type
// can be serialized/deserialized.
public bool CanConvert(Type type) {
return type == typeof(Employee);
}
// Deserializes objects of the specified type.
public object FromString(Type type, string str) {
2013 DevExpress Inc.

1948

Products

1949
if (type != typeof(Employee))
return null;
string[] array = str.Split('#');
if (array.Length >= 3)
return new Employee(array[0], array[1], int.Parse(array[2]));
else if (array.Length == 2)
return new Employee(array[0], array[1], 0);
else if (array.Length == 1)
return new Employee(array[0], string.Empty, 0);
else
return new Employee(string.Empty, string.Empty, 0);
}
// Serializes objects of the specified type.
public string ToString(Type type, object obj) {
if (type != typeof(Employee))
return string.Empty;
Employee value = obj as Employee;
return value.FirstName + '#' + value.LastName + '#' + value.Age;
}
// Returns the type by its full name.
public Type GetType(string typeName) {
if (typeName != typeof(Employee).FullName)
return null;
return typeof(Employee);
}

}
}
Visual Basic

(Form1.vb)
Imports Microsoft.VisualBasic
Imports System
Imports System.IO
Imports System.Windows.Forms
Imports DevExpress.Data.PivotGrid
Imports DevExpress.Utils.Serializing.Helpers
Namespace XtraPivotGrid_CustomObjectConverter
Partial Public Class Form1
Inherits Form
Private stream As MemoryStream
Public Sub New()
InitializeComponent()
pivotGridControl1.DataSource = DataHelper.GetData()
pivotGridControl1.OptionsData.CustomObjectConverter = _
New CustomObjectConverter()
End Sub
' Handles the Save button's Click event to save pivot grid data
' (requires data source serialization).
Private Sub simpleButton1_Click(ByVal sender As Object, ByVal e
Handles simpleButton1.Click
If stream IsNot Nothing Then
stream.Dispose()
End If
stream = New MemoryStream()
pivotGridControl1.SavePivotGridToStream(stream)
End Sub
' Handles the Load button's Click event to load pivot grid data
' (requires stream content deserialization).
Private Sub simpleButton2_Click(ByVal sender As Object, ByVal e
Handles simpleButton2.Click
If stream Is Nothing Then
2013 DevExpress Inc.

C opy C ode

to a stream
As EventArgs) _

from a stream
As EventArgs) _

1949

Products

1950

Return
End If
Dim ds As New PivotFileDataSource(stream, New CustomObjectConverter())
pivotGridControl1.DataSource = ds
End Sub
End Class
' Implements a custom serializer.
Public Class CustomObjectConverter
Implements ICustomObjectConverter
' Returns a value, indicatingwhether objects of the specified type
' can be serialized/deserialized.
Public Function CanConvert(ByVal type As Type) As Boolean _
Implements ICustomObjectConverter.CanConvert
Return type Is GetType(Employee)
End Function
' Deserializes objects of the specified type.
Public Function FromString(ByVal type As Type, ByVal str As String) As Object _
Implements ICustomObjectConverter.FromString
If type IsNot GetType(Employee) Then
Return Nothing
End If
Dim array() As String = str.Split("#"c)
If array.Length >= 3 Then
Return New Employee(array(0), array(1), Integer.Parse(array(2)))
ElseIf array.Length = 2 Then
Return New Employee(array(0), array(1), 0)
ElseIf array.Length = 1 Then
Return New Employee(array(0), String.Empty, 0)
Else
Return New Employee(String.Empty, String.Empty, 0)
End If
End Function
' Serializes objects of the specified type.
Public Overloads Function ToString(ByVal type As Type, ByVal obj As Object) As String _
Implements ICustomObjectConverter.ToString
If type IsNot GetType(Employee) Then
Return String.Empty
End If
Dim value As Employee = TryCast(obj, Employee)
Return value.FirstName + "#"c + value.LastName + "#"c + value.Age
End Function
' Returns the type by its full name.
Public Overloads Function [GetType](ByVal typeName As String) As Type _
Implements ICustomObjectConverter.GetType
If typeName IsNot GetType(Employee).FullName Then
Return Nothing
End If
Return GetType(Employee)
End Function
End Class
End Namespace

2013 DevExpress Inc.

1950

You might also like