Share via


Save and Load a DataGrid's columns graphical properties in WPF


Introduction

We'll see in this article how a user can customize a DataGrid, ordering columns or modifying their width, saving those changes for later use (i.e., when the program will show again a particular grid). Below i'll present a class apt to that end, with a simple use scenario. The code was commented to be the as clear as possible. Function were declared Shared to facilitate the static use of the class. We'll use mainly DataSet and DataTable classes, to benefit from the handy XML access methods, through which we'll realize the storage of columns parameters.

Sample Class

Imports System.Data
Public Class  emDataGridOptions
    ' We declare a certain path in which we'll store the grid's options file
    Const _DATAGRID_OPTIONS_DIR As String  = "C:\tmp\"
    ' As file extension, we'll use ".di"
    Const _DATAGRID_OPTIONS_EXT As String  = ".di"
     
    ' ===============================================================================
    ' Private function to return the full path of options file
    ' ===============================================================================
    Private Shared  Function ComposeGridOptionsFile(gridName)  As  String
        ' Simple concatenation of directory, grid's name, and default extension
        Return _DATAGRID_OPTIONS_DIR & gridName & _DATAGRID_OPTIONS_EXT
    End Function
  
    ' ===============================================================================
    ' Public shared sub to save DataGrid's option
    ' ===============================================================================
    Public Shared  Sub SaveGridOptions(dg As DataGrid)
        ' We'll create a DataSet with the same name of the Grid, generating inside it a DataTable named "columns"
         Dim columns As New  DataSet(dg.Name)
        Dim coltable As New  DataTable("columns")
  
        ' Here we'll save only some parameters, such as the visibility, the sort direction, etc.
        ' we must create in the DataTable a number of columns equals to the number of property we intend to save.
        With coltable
            .Columns.Add("DisplayIndex", Type.GetType("System.Int32"))
            .Columns.Add("Width", Type.GetType("System.Double"))
            .Columns.Add("Visibility", Type.GetType("System.Int32"))
            .Columns.Add("SortDirection", Type.GetType("System.Int32"))
        End With
  
        columns.Tables.Add(coltable)
 
        ' We execute a loop on the DataGrid's columns, adding to the DataTable a number of rows equals to the 
        ' count of DataGrid's columns, each one of them exposing the value of the property itself         
        For Each  c As  DataGridColumn In  dg.Columns
            coltable.Rows.Add(New Object() {c.DisplayIndex,
                                            c.Width.DisplayValue,
                                            c.Visibility,
                                            c.SortDirection})
        Next
  
        ' Then, using the WriteXml() method, we save an XML file which contains the columns extracted values
        columns.WriteXml(ComposeGridOptionsFile(dg.Name))
    End Sub
  
    ' ===============================================================================
    ' Public shared sub to load DataGrid's option
    ' ===============================================================================
    Public Shared  Sub LoadGridOptions(dg As DataGrid)
        ' We check if the options file exists...
         If Not  (IO.File.Exists(ComposeGridOptionsFile(dg.Name))) Then Exit  Sub
  
        ' A new DataSet will be generated, and then populated using the readXml() method
        Dim columns As New  DataSet(dg.Name)
        columns.ReadXml(ComposeGridOptionsFile(dg.Name))
 
        ' We execute a loop on grid's columns: for each of them, we read and apply the corresponding property's value from the table in DataSet
        Dim ii As Integer  = 0
        For Each  c As  DataGridColumn In  dg.Columns
  
            c.DisplayIndex = columns.Tables(0).Rows(ii).Item("DisplayIndex")
            c.Width = Double.Parse(columns.Tables(0).Rows(ii).Item("Width"))
            c.Visibility = columns.Tables(0).Rows(ii).Item("Visibility")
  
            ' The SortDirection case is a particular one: if no sort was set on a column, there will be no corresponding entity
            ' in the XML file. So, we must manage possible Nothing values
            Dim sortDirection As Nullable(Of Integer) = Nothing
            If Not  (columns.Tables(0).Rows(ii).Item("SortDirection").Equals(DBNull.Value)) Then  sortDirection = Integer.Parse(columns.Tables(0).Rows(ii).Item("SortDirection"))
 
            ' If SortDirection is specified, we need to execute the actual sort. We compile the list of sort's descriptions through the read value, plus the 
            ' column's SortMemberPath, refreshing the grid's Items.
            If Not  (sortDirection Is  Nothing) Then
                c.SortDirection = sortDirection
                dg.Items.SortDescriptions.Add(New ComponentModel.SortDescription(c.SortMemberPath, c.SortDirection))
                dg.Items.Refresh()
            End If
            ii += 1
        Next
    End Sub
End Class

Use scenario

The typical scenario is represented by entering a Window (in case of parameters loading), and from closing it at the end of the program's life-cycle (for saving). Assuming we have a Window named MainWindow, on top of which we create a DataGrid named DataGrid1, we could use Loaded() and Closing() events (if in an event-driven model), respectively for option's loading and saving. In those event's context, it will be possible to call on the static functions, feeding them the grid's name as a parameter.

Private Sub  MainWindow_Loaded(sender As Object, e As  RoutedEventArgs) Handles Me.Loaded
   'Eseguire qui le operazioni preliminari, tra cui il binding dei dati sulla griglia
    emDataGridOptions.LoadGridOptions(DataGrid1)
End Sub
  
Private Sub  MainWindow_Closing(sender As Object, e As  ComponentModel.CancelEventArgs) Handles Me.Closing
    emDataGridOptions.SaveGridOptions(DataGrid1)
End Sub