Pivot Table
Pivot Table
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
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
1855
Products
1856
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"
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:
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.
1860
Products
1861
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})
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
1862
Products
1863
1863
Products
1864
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
1864
Products
1865
1865
Products
1866
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
1867
Products
1868
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
1868
Products
1869
C opy C ode
1869
Products
1870
C opy C ode
C opy C ode
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
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
1872
Products
1873
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;
}
}
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
1874
Products
1875
Clicking the third cell in the 1994 column w ill invoke the following form:
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();
}
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
1876
Products
1877
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.
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
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";
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);
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.
1882
Products
1883
1883
Products
1884
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"
1884
Products
1885
C#
C opy C ode
C opy C ode
1885
Products
1886
1886
Products
1887
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")
1887
Products
1888
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 :
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 :
1889
Products
1890
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();
}
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
1891
Products
1892
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
1892
Products
1893
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
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
1894
Products
1895
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"))) {
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
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>
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
1900
Products
1901
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)
1901
Products
1902
1902
Products
1903
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'"
1903
Products
1904
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
1904
Products
1905
1905
Products
1906
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
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
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
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
1911
Products
1912
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
1912
Products
1913
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, _
1913
Products
1914
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
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
1916
Products
1917
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})
1917
Products
1918
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
1919
Products
1920
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);
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
1922
Products
1923
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)
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
1924
Products
1925
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();
}
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
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
1928
Products
1929
C#
C opy C ode
C opy C ode
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
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
1931
Products
1932
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
1933
Products
1934
C opy C ode
pivotGridControl1.ExportToXls("c:\\pivotGrid_output.xls");
Visual Basic
C opy C ode
PivotGridControl1.ExportToXls("c:\pivotGrid output.xls")
1934
Products
1935
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.
1935
Products
1936
1936
Products
1937
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)
1937
Products
1938
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
1939
Products
1940
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
1940
Products
1941
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)
1941
Products
1942
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);
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
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
1944
Products
1945
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
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
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
1947
Products
1948
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
1950