windowsforms-2404-common-features-saving-and-restoring-layouts-to-a-file-stream-and-system-registry.md
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.
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.
Form.FormClosed event fires and restores the saved layout when the Form.Load event fires.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.
string fileName = "gridlayout.xml";
gridView1.SaveLayoutToXml(fileName);
// …
gridView1.RestoreLayoutFromXml(fileName);
Dim fileName As String = "gridlayout.xml"
gridView1.SaveLayoutToXml(fileName)
' …
GridView1.RestoreLayoutFromXml(fileName)
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);
}
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
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);
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)
string regKey = "DevExpress\\XtraGrid\\Layouts\\MainLayout";
advBandedGridView1.SaveLayoutToRegistry(regKey);
// …
advBandedGridView1.RestoreLayoutFromRegistry(regKey);
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.
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.
DevExpress controls contain settings to customize the layout save/restore operations. These settings allow you to specify:
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.
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.
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.
DevExpress.Utils.OptionsLayoutGrid options = new DevExpress.Utils.OptionsLayoutGrid();
options.StoreAppearance = true;
gridView1.SaveLayoutToXml("gridlayout.xml", options);
//…
gridView1.RestoreLayoutFromXml("gridlayout.xml", options);
Dim options As New DevExpress.Utils.OptionsLayoutGrid()
options.StoreAppearance = True
GridView1.SaveLayoutToXml("gridlayout.xml", options)
'…
GridView1.RestoreLayoutFromXml("gridlayout.xml", options)
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.
gridView1.LayoutUpgrade += (s, ea) => {
GridView view = s as GridView;
view.Columns["ID"].Visible = false;
};
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.
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.
gridView1.BeforeLoadLayout += (s, ea) => {
GridView view = s as GridView;
if (ea.PreviousVersion != view.OptionsLayout.LayoutVersion)
ea.Allow = false;
};
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
To serialize a custom property of a simple type (for example, int and string), mark this property with the XtraSerializableProperty attribute:
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;
}
}
}
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.
Data Grid, TreeList, and Vertical Grid controls introduce events that allow you to save/restore certain settings. These include:
PropertySerializingPropertyDeserializingThe following example demonstrates how to avoid serializing certain settings:
treeList.PropertySerializing += (s, e) => {
if(e.Owner is TreeListColumn && e.PropertyName == "Caption")
e.Allow = DefaultBoolean.False;
};
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.
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";
}
}
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
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.
Double-click the “Settings.settings” file in the Visual Studio Solution Explorer and create two entries of the String type. Set the scope of both entries to “User”.
When the application is about to close, save the UserLookAndFeel.Default.SkinName and UserLookAndFeel.Default.ActiveSvgPaletteName property values.
When the application starts, read the saved settings and pass them to the UserLookAndFeel.Default.SetSkinStyle method as parameters.
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();
}
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
See the following quick-reference guide for additional information and examples:
Save and Restore Layouts of DevExpress Controls
See Also