Serialization and Deserialization
The SfDataGrid control supports Serialization and Deserialization. The entire SfDataGrid setting can be serialized and deserialized at execute time. This section explains on how to serialize and deserialize SfDataGrid and how to customize serialization and deserialization process by using SerializationController. By customizing SerializationController, you can serialize and deserialize derived SfDataGrid and also customize column.
Overview
The SfDataGrid control includes following methods for Serialization and Deserialization.
Method | Overload | Description |
---|---|---|
Serialize | Serialize(Stream stream) | Serialize the SfDataGrid and exports its properties to given XML file. |
Serialize | Serialize(Stream stream, SerializationOptions options) | Serialize the SfDataGrid and exports its properties to given XML file based on SerializationOptions |
Serialize | Serialize(StorageFile storageFile) | Serialize the SfDataGrid and its properties to given XML file |
Serialize | Serialize(StorageFile storageFile, SerializationOptions serializationOptions) | Serialize the SfDataGrid and exports its properties to given XML file based on SerializationOptions |
Deserialize | Deserialize(Stream stream) | Reconstructs the SfDataGrid with the objects that are stored in the given XML file. |
Deserialize | Deserialize(Stream stream, DeserializationOptions options) | Reconstructs the SfDataGrid with the objects that are stored in the given XML file based on DeserializationOptions |
Deserialize | Deserialize(StorageFile storageFile) | Reconstructs the SfDataGrid with the objects that are stored in the given XML file. |
Deserialize | Deserialize(StorageFile storageFile, DeserializationOptions deserializationOptions) | Reconstructs the SfDataGrid with the objects that are stored in the given XML file based on DeserializationOptions |
When you invoke the Serialize method, it exports the current SfDataGrid control properties to an XML file and the Deserialize method reconstructs the SfDataGrid control with the objects that are stored in the XML file.
The following code example illustrates on how to use Serialization and Deserialization in the SfDataGrid control using SerializationOptions and DeserializationOptions. SerializationOptions and DeserializationOptions are a class used to specify the options for customizing serialization and deserialization respectively. You can achieve this by clicking Serialize button and when the XML file is saved, reconstruct the SfDataGrid control by clicking the Deserialize button.
<Page.DataContext>
<local:ViewModel/>
</Page.DataContext>
<syncfusion:SfDataGrid x:Name="sfGrid"
AllowDraggingColumns="True"
ColumnSizer="Star"
NavigationMode="Row"
ItemsSource="{Binding EmployeeDetails}"
ShowGroupDropArea="True">
<syncfusion:SfDataGrid.Columns>
<syncfusion:GridTextColumn MappingName="EmployeeID" />
<syncfusion:GridTextColumn HeaderText="Employee Name"
MappingName="Name" />
<syncfusion:GridTextColumn MappingName="Gender" />
<syncfusion:GridTextColumn HeaderText="Designation"
MappingName="Title" MinimumWidth="240" />
<syncfusion:GridTextColumn HeaderText="Marital Status"
MappingName="MaritalStatus" />
</syncfusion:SfDataGrid.Columns>
</syncfusion:SfDataGrid>
<StackPanel>
<StackPanel>
<TextBlock Margin="5" Text="Serialize the DataGrid" />
<Button Width="150" x:Name="serializebtn" Margin="5"
Click="OnSerializeDataGrid" Content="Serialize" />
</StackPanel>
<StackPanel>
<TextBlock Margin="5" Text="Deserialize the DataGrid" />
<Button Width="150" x:Name="deserializebtn" Margin="5"
Click="OnDeserializeDataGrid" Content="Deserialize" />
</StackPanel>
</StackPanel>
Private void OnSerializeDataGrid(object sender, RoutedEventArgs args)
{
var folder = KnownFolders.DocumentsLibrary;
try
{
var storageFile = await folder.CreateFileAsync("DataGrid.xml",CreationCollisionOption.ReplaceExisting);
SerializationOptions options = new SerializationOptions();
options.SerializeSorting = false;
this.dataGrid.Serialize(storageFile, options);
}
catch (Exception)
{
}
}
private async void OnDeserializeDataGrid(object sender, RoutedEventArgs args)
{
var folder = KnownFolders.DocumentsLibrary;
try
{
var storageFile = await folder.GetFileAsync("DataGrid.xml");
DeserializationOptions options = new DeserializationOptions();
options.DeserializeSorting = false;
this.dataGrid.Deserialize(storageFile,options);
}
catch (Exception)
{
}
}
Serialization and Deserialization Options
To customize the serialization and deserialization process, you can use SerializationOptions and DeserializationOptions respectively. Following are the list of properties provided by these classes.
SerializationOptions
Property | Type | Description | Default Value |
---|---|---|---|
SerializeSorting | Boolean | Gets or sets the value that determines whether the method serialize SfDataGrid’s SortColumnDescriptions | True |
SerializeGrouping | Boolean | Gets or sets the value that determines whether the method serialize SfDataGrid’s GroupColumnDescriptions | True |
SerializeGroupSummaries | Boolean | Gets or sets the value that determines whether the method serialize GroupSummaryRows | True |
SerializeCaptionSummary | Boolean | Gets or sets the value that determines whether the method serialize CaptionSummaryRow | True |
SerializeTableSummaries | Boolean | Gets or sets the value that determines whether the method serialize TableSummaryRows | True |
SerializeFiltering | Boolean | Gets or sets the value that determines whether the method serialize columns FilterPredicates | True |
SerializeColumns | Boolean | Gets or sets the value that determines whether the method serialize grid Columns | True |
SerializeStackedHeaders | Boolean | Gets or sets the value that determines whether the method serialize StackedHeaderRows | True |
DeserializationOptions
Property | Type | Description | Default Value |
---|---|---|---|
DeserializeSorting | Boolean | Gets or sets a value that determines whether the method deserialize SfDataGrid’s SortColumnDescriptions | True |
DeserializeGrouping | Boolean | Gets or sets a value that determines whether the method deserialize SfDataGrid’s GroupColumnDescriptions | True |
DeserializeGroupSummaries | Boolean | Gets or sets a value that determines whether the method deserialize GroupSummaryRows | True |
DeserializeCaptionSummary | Boolean | Gets or sets a value that determines whether the method deserialize CaptionSummaryRow | True |
DeserializeTableSummaries | Boolean | Gets or sets a value that determines whether the method deserialize TableSummaryRows | True |
DeserializeFiltering | Boolean | Gets or sets a value that determines whether the method deserialize columns FilterPredicates | True |
DeserializeColumns | Boolean | Gets or sets a value that determines whether the method deserialize SfDataGrid’s Columns | True |
DeserializeStackedHeaders | Boolean | Gets or sets a value that determines whether the method deserialize StackedHeaderRows | True |
Overriding SerializationController
SerializationController is a public class that handles serialization and deserialization operations in SfDataGrid. DataContractSerializer is used in SerializationController to perform serialization and deserialization.By overriding SerializationController, you can customize serialization and deserialization operations. SerializationController copies the SfDataGrid and its inner class properties to SerializableDataGrid (This class is serialized only using DataContractSerializer). Similarly SerializableDataGrid, GridColumn properties that are to be serialized is copied into SerializableGridColumn. Also GroupColumnDescriptions, SortColumnDescriptions, StackedHeaders and etc., is copied to its corresponding serializable classes.
SerializationController contains the following methods to perform serialization and deserialization operations.
Method | Description |
---|---|
public virtual void Serialize(Stream stream, SerializationOptions serializeOptions) | Method used to serialize the SfDataGrid and exports its properties to given XML file.This method is useful when you serialize derived data grid. |
protected virtual SerializableDataGrid StoreGridSettings(SerializationOptions serializeOptions) | Called during serialization process to copy grid properties, sorting, filtering, grouping, etc.to SerializableDataGrid from SfDataGrid |
protected virtual void StoreGridProperties(SerializableDataGrid serializableDataGrid) | Called during serialization process to copy grid properties to SerializableDataGrid. |
protected virtual SerializableDataGrid GetSerializableDataGrid() | Called to get SfDataGrid instance while serializing grid. It is useful while serializing custom data grid. When you want to serialize the custom SfDataGrid properties, you should add these properties to custom SerializableDataGrid class. |
protected virtual SerializableGridColumn GetSerializableGridColumn(GridColumn column) | Called to get serializable grid column instance while serializing grid. It is useful while serializing custom column. |
protected virtual SerializableFilterSettings StoreFilterPredicates(SfDataGrid dataGrid) | Called during serialization process to copy filter predicates to SerializableFilterSettings |
protected virtual void StoreGridColumnProperties(GridColumn column, SerializableGridColumn serializableColumn) | Called during serialization process to copy grid column properties to SerializableGridColumn |
protected virtual SerializableColumns StoreGridColumns(SfDataGrid dataGrid) | Called during serialization process to copy grid columns to SerializableColumns |
protected virtual SerializableStackedHeaderRow StoreGridStackedHeaderRow(StackedHeaderRow stackedHeaderRow) | Called during serialization process to copy grid stacked header row to SerializableStackedHeaderRow. |
protected virtual SerializableGridSummaryRow StoreGridSummaryRow(GridSummaryRow gridSummaryRow, SerializableGridSummaryRow serializableSummaryRow = null) | Called during serialization process to copy grid summary row from SfDataGrid to SerializableGridSummaryRow |
protected virtual SerializableGroupColumnDescriptions StoreGroupColumnDescriptions(SfDataGrid dataGrid) | Called during serialization process to copy group column descriptions from SfDataGrid to SerializableGroupColumnDescriptions |
protected virtual SerializableSortColumnDescriptions StoreSortColumnDescriptions(SfDataGrid dataGrid) | Called during serialization process to copy sort column descriptions to SerializableSortColumnDescriptions. |
public virtual void Deserialize(Stream stream, DeserializationOptions deserializeOptions) | Method used to deserialize the SfDataGrid. It reconstructs the SfDataGrid with the objects that are stored in the given XML file.This method is useful while deserializing derived data grid. |
protected virtual void ReloadGrid(SerializableDataGrid dataGrid, DeserializationOptions deserializationOptions) | Called during deserialization process to restore grid properties from SerializableDataGrid and reload the grid |
protected virtual void UnWireSerializablePropertyEvents() | Called during serialization process to unwire SortColumnDescriptions, GroupColumnDescriptions collection changed, etc. event |
protected virtual void RestoreGridSettings(SerializableDataGrid serializableDataGrid, SfDataGrid dataGrid, DeserializationOptions options) | Called during deserialization process to restore grid properties, sorting, filtering, grouping, etc. from SerializableDataGrid |
protected virtual void RestoreGridProperties(SerializableDataGrid serializableDataGrid) | Called during deserialization process to copy grid properties from SerializableDataGrid |
protected virtual void RestoreGridColumns(SerializableDataGrid serializableDataGrid) | Called during deserialization process to copy grid columns from SerializableDataGrid |
protected virtual GridColumn GetGridColumn(SerializableGridColumn serializableColumn) | Called to get GridColumn instance while deserializing grid. It is useful while deserializing custom column. The returned grid column is added to SfDataGrid columns collection while deserializing. |
protected virtual void RestoreColumnProperties(SerializableGridColumn serializableColumn, GridColumn column) | Called during deserialization process to copy grid column properties from SerializableGridColumn |
protected virtual void RestoreFilterPredicates(SerializableDataGrid serializableDataGrid) | Called during deserialization process to copy filter predicates from SerializableDataGrid |
protected virtual StackedHeaderRow RestoreGridStackedHeaderRow(SerializableStackedHeaderRow serializableStackedHeaderRow) | Called during deserialization process to restore grid stacked header row from SerializableStackedHeaderRow |
protected virtual GridSummaryRow RestoreGridSummaryRow(SerializableGridSummaryRow serializableGridSummaryRow, GridSummaryRow summaryRow = null) | Called during deserialization process to restore grid summary row from SerializableGridSummaryRow |
protected virtual void RestoreGroupColumnDescriptions(SerializableDataGrid serializableDataGrid) | Called during deserialization process to restore group column descriptions from SerializableDataGrid |
protected virtual void RestoreSortColumnDescriptions(SerializableDataGrid serializableDataGrid) | Called during deserialization process to restore sort column descriptions from SerializableDataGrid |
protected virtual void WireSerializablePropertyEvents() | Called during Deserialization process to wire SortColumnDescriptions, GroupColumnDescriptions collection changed, etc. event |
public virtual Type[] KnownTypes() | Called during serialization and deserialization operations. It is useful while using custom columns. When you want to serialize the columns, its types should be returned as a list |
public virtual void Dispose() | Method used to dispose SerializationController |
Property | Type | Description | Default Value |
---|---|---|---|
DataGrid | SfDataGrid | Gets the SfDataGrid instance to copy properties from/to SerializableDataGrid | Null |
The following code example illustrates to override methods and how to handle operations in SerializationController. SerializationControllerExt class is derived from SerializationController and you can assign this to existing SerializationController. SerializationControllerExt overrides existing one.
// Assign custom serialization controller to datagrid SerializationController
this.dataGrid.SerializationController = new SerializationControllerExt(this.dataGrid);
/// <summary>
/// SerializationControllerExt class is the custom SerializationController
/// </summary>
public class SerializationControllerExt : SerializationController
{
public SerializationControllerExt(SfDataGrid grid)
: base(grid)
{
}
/// <summary>
/// Store grid settings - properties, columns, sort descriptions,group descriptions, stacked headers, filter predicates, summaries
/// </summary>
/// <param name="serializeOptions">options for serializing grid</param>
/// <returns>SerializableDataGrid</returns>
protected override SerializableDataGrid StoreGridSettings(SerializationOptions serializeOptions)
{
return base.StoreGridSettings(serializeOptions);
}
/// <summary>
/// Restore grid properties,columns,sort descriptions,group descriptions,filter predicates,stacked headers,summaries
/// </summary>
/// <param name="serializableDataGrid">serializableDataGrid instance</param>
/// <param name="dataGrid">SfDataGrid</param>
/// <param name="options">DeserializationOptions</param>
protected override void RestoreGridSettings(SerializableDataGrid serializableDataGrid, SfDataGrid dataGrid, DeserializationOptions options)
{
base.RestoreGridSettings(serializableDataGrid, dataGrid, options);
}
}
How To
How to retain new columns when you deserialize SfDataGrid
By default, the columns that exist in the SfDataGrid when you apply serialization alone are displayed after deserializing the SfDataGrid. When you want to preserve the columns that currently exist in the SfDataGrid while applying deserialization, but not in the layout while serialization, customize SerializationController to achieve this. The following code example illustrates how to customize SerializationController.
<syncfusion:SfDataGrid x:Name="sfGrid"
AutoGenerateColumns="False"
ColumnSizer="Star"
ItemsSource="{Binding EmployeeDetails}"
NavigationMode="Row"
ShowGroupDropArea="True">
<syncfusion:SfDataGrid.Columns>
<syncfusion:GridTextColumn HeaderText="Employee ID" MappingName="EmployeeID" />
<syncfusion:GridTextColumn HeaderText="Employee Name" MappingName="Name" />
<syncfusion:GridTextColumn MappingName="Gender" />
<syncfusion:GridTextColumn HeaderText="Designation"
MappingName="Title"
MinimumWidth="240" />
</syncfusion:SfDataGrid.Columns>
</syncfusion:SfDataGrid>
After serialization, when new column is added to SfDataGrid, it is not displayed during deserialization.
// To add new unbound column at run time
dataGrid.Columns.Add(new GridUnBoundColumn() { MappingName = "UnboundColumn", Expression = "2 *EmployeeID" });
The following screenshot illustrates the SfDataGrid after deserialization.
You can overcome the above scenario by customizing the SerializationController and refer to the following code example that illustrates how to preserve the new unbound column during deserialization.
// Assigning custom serialization controller to datagrid SerializationController
dataGrid.SerializationController = new SerializationControllerExt(dataGrid);
/// <summary>
/// SerializationControllerExt class is the custom SerializationController
/// </summary>
public class SerializationControllerExt : SerializationController
{
public SerializationControllerExt(SfDataGrid dataGrid)
: base(dataGrid)
{
}
/// <summary>
/// Restore grid columns from serializableDataGrid
/// </summary>
/// <param name="serializableDataGrid"></param>
protected override void RestoreGridColumns(SerializableDataGrid serializableDataGrid)
{
foreach (var serializableColumn in serializableDataGrid.Columns)
{
var column = GetGridColumn(serializableColumn);
RestoreColumnProperties(serializableColumn, column);
if (!this.Datagrid.Columns.Any(x => x.MappingName.Equals(column.MappingName)))
this.Datagrid.Columns.Add(column);
}
}
}
The following screenshot illustrates the output image after deserializing SfDataGrid using custom serialization controller.
How to serialize custom column in SfDataGrid
By default, the grid columns are serialized during serialization of SfDataGrid. But when custom column is added in SfDataGrid, it is not serialized. Since DataContractSerializer is used the custom column type has to be identified to serialize and deserialize the custom column. To serialize the custom column, you can override SerializationController. Refer to the following code example.
public class DatePickerColumn : GridColumn
{
public static readonly DependencyProperty DateMappingNameProperty = DependencyProperty.Register("DateMappingName",
typeof(string), typeof(DatePickerColumn));
public DatePickerColumn()
{
SetCellType("DatePickerRenderer");
}
public string DateMappingName
{
get { return (string)GetValue(DateMappingNameProperty); }
set { SetValue(DateMappingNameProperty, value); }
}
protected override Freezable CreateInstanceCore()
{
return new DatePickerColumn();
}
}
Consider, the SfDataGrid contains the following columns. Here DatePickerColumn is custom column.
<Syncfusion:SfDataGrid x:Name="_dataGrid"
AutoGenerateColumns="False"
ColumnSizer="Star"
ItemsSource="{Binding Path=DataItems}>
<Syncfusion:SfDataGrid.Columns>
<Syncfusion:GridTextColumn AllowEditing="True" MappingName="ItemNumber"/>
<demo:DatePickerColumn AllowEditing="True"
DateMappingName="Date"
HeaderText="DatePickerColumn"
MappingName="Date" />
</Syncfusion:SfDataGrid.Columns>
</Syncfusion:SfDataGrid>
During SfDataGrid serialization, when you want to copy DatePickerColumn properties, you can create the SerializableCustomGridColumn (derived from SerializableGridColumn) class containing the properties as follows.
[DataContract(Name="SerializableCustomGridColumn")]
public class SerializableCustomGridColumn : SerializableGridColumn
{
[DataMember]
public string DateMappingName { get; set; }
}
The following code illustrates how to override SerializationController to serialize custom column.
// Assigning custom serialization controller to datagrid SerializationController
dataGrid.SerializationController = new SerializationControllerExt(dataGrid);
/// <summary>
/// SerializationControllerExt class is the custom SerializationController
/// </summary>
public class SerializationControllerExt : SerializationController
{
public SerializationControllerExt(SfDataGrid dataGrid)
: base(dataGrid)
{
}
/// <summary>
/// Get grid column instance for deserialization
/// </summary>
/// <param name="serializableColumn">serializableColumn</param>
/// <returns>GridColumn</returns>
protected override GridColumn GetGridColumn(SerializableGridColumn serializableColumn)
{
if (serializableColumn is SerializableCustomGridColumn)
return new DatePickerColumn();
return base.GetGridColumn(serializableColumn);
}
/// <summary>
/// Get serializable grid column instance
/// </summary>
/// <param name="column">grid column</param>
/// <returns>SerializableGridColumn</returns>
protected override SerializableGridColumn GetSerializableGridColumn(GridColumn column)
{
if (column.MappingName == "Date")
{
return new SerializableCustomGridColumn();
}
return base.GetSerializableGridColumn(column);
}
/// <summary>
/// Store Grid Column Properties to serializable grid column
/// </summary>
/// <param name="column">grid column</param>
/// <param name="serializableColumn">serializableColumn</param>
protected override void StoreGridColumnProperties(GridColumn column, SerializableGridColumn serializableColumn)
{
base.StoreGridColumnProperties(column, serializableColumn);
if (column is DatePickerColumn)
(serializableColumn as SerializableCustomGridColumn).DateMappingName = (column as DatePickerColumn).DateMappingName;
}
/// <summary>
/// Restore grid column properties from SerializableGridColumn
/// </summary>
/// <param name="serializableColumn">serializableColumn</param>
/// <param name="column">grid column</param>
protected override void RestoreColumnProperties(SerializableGridColumn serializableColumn, GridColumn column)
{
base.RestoreColumnProperties(serializableColumn, column);
if (column is DatePickerColumn)
(column as DatePickerColumn).DateMappingName = (serializableColumn as SerializableCustomGridColumn).DateMappingName;
}
/// <summary>
/// Get known types of serializable columns for serialization and deserialization
/// </summary>
/// <returns></returns>
public override Type[] KnownTypes()
{
var types = base.KnownTypes();
var list = types.Cast<Type>().ToList();
list.Add(typeof(SerializableCustomGridColumn));
return list.ToArray();
}
}