Click here to Skip to main content
15,879,095 members
Articles / Desktop Programming / WPF
Tip/Trick

Save and Load a DataGrid's Columns Graphical Properties in WPF

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
3 Jan 2015CPOL 10.8K   2   3
How to save DataGrid column's properties for further re-use

Introduction

We'll see in this tip how a user can customize a DataGrid, ordering columns or modifying their width, saving those changes for a 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 most clear as possible. Function was 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

VB.NET
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 most typical scenario is certainly 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.

VB.NET
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

History

  • 2015-01-03: First release for CodeProject

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
Italy Italy
Working in IT since 2003 as Software Developer for Essetre Srl, a company in Northern Italy.
I was awarded in 2014, 2015 and 2016 with Microsoft MVP, for Visual Studio and Development Technologies expertise. My technology interests and main skills are in .NET Framework, Visual Basic, Visual C# and SQL Server, but i'm proficient in PHP and MySQL also.

Comments and Discussions

 
Generalthanks Pin
Hooman_Kh5-Jan-15 13:27
Hooman_Kh5-Jan-15 13:27 
GeneralRe: thanks Pin
Emiliano Musso6-Jan-15 5:53
professionalEmiliano Musso6-Jan-15 5:53 
GeneralRe: thanks Pin
Hooman_Kh8-Jan-15 12:02
Hooman_Kh8-Jan-15 12:02 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.