How to: Save and Restore the Collapsed State of the Field Values

  • 2 minutes to read

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 will be restored when you click the Load button.

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();
        }
    }
}