Back to Devexpress

Save and Restore Layouts of DevExpress Controls

windowsforms-2404-common-features-saving-and-restoring-layouts-to-a-file-stream-and-system-registry.md

latest19.1 KB
Original Source

Save and Restore Layouts of DevExpress Controls

  • Mar 25, 2025
  • 8 minutes to read

DevExpress controls allow you to save their layout information to data stores (XML file, stream and system registry) and then restore it. Different controls save different sets of options. Typically, the saved layout includes the visibility, position, and size of visual elements, and their sort, group, summary, and filter settings.

You can customize which properties need to be saved/restored and perform actions on layout loading.

Important

Deserializing layout settings from untrusted resources may create security issues. Review the following help topic for additional information: Safe Deserialization.

Save and Restore the Form’s Bounds, State, Layouts of Child Controls

You can use the following components to save/restore a form’s bounds/state along with the layouts of all DevExpress controls that reside within this form.

  • Persistence Behavior (part of the Behavior Feature) - Automatically saves the layout information to a file or the system registry when the Form.FormClosed event fires and restores the saved layout when the Form.Load event fires.
  • Workspace Manager - Allows you to manually save the layout information to a file, stream or system registry. Supports multiple layouts (workspaces) and animation effects. Allows you to prevent serialization/deserialization of specific properties.

Save and Restore Layouts of Individual Controls

DevExpress controls and components contain methods used to save/restore their layouts to/from a file/stream/system registry.

Save LayoutSaveLayoutToRegistry, SaveLayoutToStream, SaveLayoutToXml, SaveLayoutToJsonRestore LayoutRestoreLayoutFromRegistry, RestoreLayoutFromStream, RestoreLayoutFromXml, RestoreLayoutFromJson

You cannot save multiple layouts to a single data store when using these methods. Use Workspace Manager to save multiple layouts to a single file, stream or system registry.

Example: Save Layout to XML

csharp
string fileName = "gridlayout.xml";
gridView1.SaveLayoutToXml(fileName);
// …
gridView1.RestoreLayoutFromXml(fileName);
vb
Dim fileName As String = "gridlayout.xml"
gridView1.SaveLayoutToXml(fileName)
' …
GridView1.RestoreLayoutFromXml(fileName)

Example: Save Layout to JSON

csharp
string filePath = "gridlayout.json";
void Form1_Load(object sender, EventArgs e) {
    if (File.Exists(filePath)) {
        using (var jsonStream = File.OpenRead(filePath))
            gridView1.RestoreLayoutFromJson(jsonStream);
    }
}

void Form1_FormClosing(object sender, FormClosingEventArgs e) {
    using (var jsonStream = File.OpenWrite(filePath))
        gridView1.SaveLayoutToJson(jsonStream);
}
vb
Private filePath As String = "gridlayout.json"
Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs)
    If File.Exists(filePath) Then
        Using jsonStream = File.OpenRead(filePath)
            gridView1.RestoreLayoutFromJson(jsonStream)
        End Using
    End If
End Sub

Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As FormClosingEventArgs)
    Using jsonStream = File.OpenWrite(filePath)
        gridView1.SaveLayoutToJson(jsonStream)
    End Using
End Sub

Example: Save Layout to a Stream

csharp
System.IO.Stream str;
//…
// Save the layout to a new memory stream.
str = new System.IO.MemoryStream();
gridControl1.FocusedView.SaveLayoutToStream(str);
str.Seek(0, System.IO.SeekOrigin.Begin);

// …
// Load the saved layout.
gridControl1.FocusedView.RestoreLayoutFromStream(str);
str.Seek(0, System.IO.SeekOrigin.Begin);
vb
Dim str As System.IO.Stream
'…
' Save the layout to a new memory stream.
str = New System.IO.MemoryStream()
GridControl1.FocusedView.SaveLayoutToStream(str)
str.Seek(0, System.IO.SeekOrigin.Begin)

' …
' Load the saved layout.
GridControl1.FocusedView.RestoreLayoutFromStream(str)
str.Seek(0, System.IO.SeekOrigin.Begin)

Example: Save Layout to the System Registry

csharp
string regKey = "DevExpress\\XtraGrid\\Layouts\\MainLayout";
advBandedGridView1.SaveLayoutToRegistry(regKey);
// …
advBandedGridView1.RestoreLayoutFromRegistry(regKey);
vb
Dim regKey As String = "DevExpress\XtraGrid\Layouts\MainLayout"
AdvBandedGridView1.SaveLayoutToRegistry(regKey)
' …
AdvBandedGridView1.RestoreLayoutFromRegistry(regKey)

Note

When you save a layout to the system registry, you can define an absolute or relative registry key as a destination. For instance, when you specify the “Software\MyCompany\MyProject" destination, the actual path will be the “HKEY_CURRENT_USER\Software\MyCompany\MyProject" path.

When to Call “SaveLayoutTo…” and “RestoreLayoutFrom…” Methods

You can handle the Form.Load/UserControl.Load events to restore control layouts.

Handle the Form.FormClosing event to save layouts of controls positioned within a form. For controls that reside within a UserControl, override the UserControl.Dispose method.

Layout Options

DevExpress controls contain settings to customize the layout save/restore operations. These settings allow you to specify:

  • which properties are saved/restored;

Tip

If you use Workspace Manager to save/restore layouts, the following events allow you to prevent serialization/deserialization of specific properties: WorkspaceManager.PropertySerializing and WorkspaceManager.PropertyDeserializing.

  • whether or not new items are retained after you load an old layout;
  • whether or not to discard the items that do not exist in the control, but exist in the loaded layout;
  • the layout version.

The list below shows the objects used to access these layout-specific settings.

For information on the options available in the Data Grid and Pivot Grid controls, see the following topic: Layout Options (XtraGrid, XtraPivotGrid).

The layout-specific settings the DevExpress controls expose affect all save/restore operations (when you use Persistence Behavior, Workspace Manager or call control. SaveLayoutTo… and control. RestoreLayoutFrom… default overloads).

The controls’ SaveLayoutTo… and RestoreLayoutFrom… methods have overloads with and without the options parameter. For instance, the overloads of the BaseView.SaveLayoutToXml and BaseView.RestoreLayoutFromXml methods are declared as follows.

csharp
public void SaveLayoutToXml(string xmlFile)
public void SaveLayoutToXml(string xmlFile, OptionsLayoutBase options)

public void RestoreLayoutFromXml(string xmlFile)
public void RestoreLayoutFromXml(string xmlFile, OptionsLayoutBase options)

The default overloads (without the options parameter) take into account the layout-specific settings exposed by the control. The overloads that have the options parameter take into account the specified settings and ignore the layout-specific settings exposed by the control.

csharp
DevExpress.Utils.OptionsLayoutGrid options = new DevExpress.Utils.OptionsLayoutGrid();
options.StoreAppearance = true;
gridView1.SaveLayoutToXml("gridlayout.xml", options);
//…
gridView1.RestoreLayoutFromXml("gridlayout.xml", options);
vb
Dim options As New DevExpress.Utils.OptionsLayoutGrid()
options.StoreAppearance = True
GridView1.SaveLayoutToXml("gridlayout.xml", options)
'…
GridView1.RestoreLayoutFromXml("gridlayout.xml", options)

Post-restore customization

After a layout is restored, you can perform additional customization in a control’s LayoutUpgrade event handler. In the “Customize layout during restoration” demo, a Data Grid’s BaseView.LayoutUpgrade event is handled to hide the first column.

csharp
gridView1.LayoutUpgrade += (s, ea) => {
    GridView view = s as GridView;
    view.Columns["ID"].Visible = false;
};
vb
AddHandler GridView1.LayoutUpgrade, Sub(s, ea)
    Dim view As GridView = TryCast(s, GridView)
    view.Columns("ID").Visible = False
End Sub

A control’s OptionsLayout.LayoutVersion property allows you to explicitly label different layout versions. The LayoutUpgrade event is raised only when the loaded layout version differs from the currently active one.

See the following topic for more information: Upgrading Layout.

Cancel Layout Restore Operations

You can handle a control’s BeforeLoadLayout event to prevent a layout from being loaded in certain cases. For example, you can cancel the restore operation if the loaded layout’s version does not match the control’s LayoutVersion.

csharp
gridView1.BeforeLoadLayout += (s, ea) => {
    GridView view = s as GridView;
    if (ea.PreviousVersion != view.OptionsLayout.LayoutVersion)
        ea.Allow = false;
};
vb
AddHandler GridView1.BeforeLoadLayout, Sub(s, ea)
    Dim view As GridView = TryCast(s, GridView)
    If ea.PreviousVersion <> view.OptionsLayout.LayoutVersion Then ea.Allow = False
End Sub

Serialize a Custom Property of a DevExpress Control’s Descendant

To serialize a custom property of a simple type (for example, int and string), mark this property with the XtraSerializableProperty attribute:

csharp
public class MyGridColumn : GridColumn {
    public MyGridColumn() : base() { }

    private int oldVisibleIndex = -1;
    [XtraSerializableProperty, XtraSerializablePropertyId(LayoutIdLayout)]
    public int OldVisibleIndex {
        get { return oldVisibleIndex; }
        set {
            if (value == -1) return;
            oldVisibleIndex = value; 
        }
    }
}
vb
Public Class MyGridColumn
    Inherits GridColumn
    Public Sub New()
        MyBase.New()
    End Sub

    Private oldVisibleIndex_Renamed As Integer = -1
    <XtraSerializableProperty, XtraSerializablePropertyId(LayoutIdLayout)> _
    Public Property OldVisibleIndex() As Integer
        Get
            Return oldVisibleIndex_Renamed
        End Get
        Set(ByVal value As Integer)
            If value = -1 Then
                Return
            End If
            oldVisibleIndex_Renamed = value
        End Set
    End Property
End Class

Tip

For information on how to serialize properties of complex types and collection properties, see the following KB article: How to serialize a custom property of the DevExpress control’s descendant.

Prevent Property Serialization/Deserialization

Data Grid, TreeList, and Vertical Grid controls introduce events that allow you to save/restore certain settings. These include:

  • PropertySerializing
  • PropertyDeserializing

The following example demonstrates how to avoid serializing certain settings:

csharp
treeList.PropertySerializing += (s, e) => {
    if(e.Owner is TreeListColumn && e.PropertyName == "Caption")
        e.Allow = DefaultBoolean.False;
};
vb
AddHandler treeList.PropertySerializing, Sub(s, e)
    If TypeOf e.Owner Is TreeListColumn AndAlso e.PropertyName = "Caption" Then
        e.Allow = DefaultBoolean.False
    End If
End Sub

Use the Workspace Manager component to save/restore the layout of all controls and manage which individual properties need to be saved/restored. The component contains the WorkspaceManager.PropertySerializing and WorkspaceManager.PropertyDeserializing events to handle save/restore operations of individual properties of controls and components.

csharp
void workspaceManager1_PropertyDeserializing(object sender, DevExpress.Utils.PropertyCancelEventArgs ea) {
    GridView view = ea.Component as GridView;
    if (view != null && view == gridView1) {
        ea.Cancel = ea.PropertyName == "MultiSelect";
    }
}
vb
Sub WorkspaceManager1_PropertyDeserializing(sender As Object, ea As DevExpress.Utils.PropertyCancelEventArgs) Handles WorkspaceManager1.PropertyDeserializing
    Dim view As GridView = TryCast(ea.Component, GridView)
    If Not view Is Nothing AndAlso view Is GridView1 Then
        ea.Cancel = ea.PropertyName = "MultiSelect"
    End If
End Sub

Save/Restore Various Settings

The SaveLayout… methods, Workspace Manager and Persistence Behavior do not save settings other than control layout options.

You can use the standard Windows Forms Application Settings feature to save/restore any setting. It allows you to store and maintain custom application and user preferences on client computers.

For example, do the following to save and restore the active skin and skin palette.

csharp
public Form1() {
    InitializeComponent();

    var settings = Properties.Settings.Default;
    if(!String.IsNullOrEmpty(settings.SkinName)) {
        if(!String.IsNullOrEmpty(settings.SkinName)) {
            UserLookAndFeel.Default.SetSkinStyle(settings.SkinName, settings.Palette);
        }
        else
            UserLookAndFeel.Default.SetSkinStyle(settings.SkinName);
    }
}

private void Form1_FormClosing(object sender, FormClosingEventArgs e) {
    var settings = Properties.Settings.Default;
    settings.SkinName = UserLookAndFeel.Default.SkinName;
    settings.Palette = UserLookAndFeel.Default.ActiveSvgPaletteName;
    settings.Save();
}
vb
Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As FormClosingEventArgs)
    Dim settings = My.Settings.Default
    settings.SkinName = UserLookAndFeel.Default.SkinName
    settings.Palette = UserLookAndFeel.Default.ActiveSvgPaletteName
    settings.Save()
End Sub

Public Sub New()
    InitializeComponent()

    Dim settings = My.Settings.Default
    If Not String.IsNullOrEmpty(settings.SkinName) Then
        If Not String.IsNullOrEmpty(settings.SkinName) Then
            UserLookAndFeel.Default.SetSkinStyle(settings.SkinName, settings.Palette)
        Else
            UserLookAndFeel.Default.SetSkinStyle(settings.SkinName)
        End If
    End If
End Sub

Cheat Sheets and Best Practices

See the following quick-reference guide for additional information and examples:

Save and Restore Layouts of DevExpress Controls

See Also

Layout Options (Grid, Pivot Grid, TreeList, Vertical Grid)

Upgrading Layout

How to Perform Actions On Application Startup