Load & Save configuration

using System;
using System.Collections.Generic;
using System.IO;
using System.Windows.Forms;
using System.Xml.Serialization;

namespace DataGridViewExtensions
{
    [Serializable]
    public sealed class ColumnInfo
    {
        public string Name { get; set; }
        public int DisplayIndex { get; set; }
        public int Width { get; set; }
        public bool Visible { get; set; }
    }

    public static class DataGridViewExtenstions
    {
        /// <summary>
        /// Loads columns information from the specified XML file
        /// </summary>
        /// <param name="dgv">DataGridView control instance</param>
        /// <param name="fileName">XML configuration file</param>
        public static void LoadConfiguration(this DataGridView dgv, string fileName)
        {
            List<ColumnInfo> columns;
            using (var streamReader = new StreamReader(fileName))
            {
                var xmlSerializer = new XmlSerializer(typeof(List<ColumnInfo>));
                columns = (List<ColumnInfo>)xmlSerializer.Deserialize(streamReader);
            }
            foreach (var column in columns)
            {
                dgv.Columns[column.Name].DisplayIndex = column.DisplayIndex;
                dgv.Columns[column.Name].Width = column.Width;
                dgv.Columns[column.Name].Visible = column.Visible;
            }
        }

        /// <summary>
        /// Saves columns information to the specified XML file
        /// </summary>
        /// <param name="dgv">DataGridView control instance</param>
        /// <param name="fileName">XML configuration file</param>
        public static void SaveConfiguration(this DataGridView dgv, string fileName)
        {
            var columns = new List<ColumnInfo>();
            for (int i = 0; i < dgv.Columns.Count; i++)
            {
                var column = new ColumnInfo();
                column.Name = dgv.Columns[i].Name;
                column.DisplayIndex = dgv.Columns[i].DisplayIndex;
                column.Width = dgv.Columns[i].Width;
                column.Visible = dgv.Columns[i].Visible;
                columns.Add(column);
            }            
            using (var streamWriter = new StreamWriter(fileName))
            {
                var xmlSerializer = new XmlSerializer(typeof(List<ColumnInfo>));
                xmlSerializer.Serialize(streamWriter, columns);
            }
        }
    }
}
Example:
dgvInstance.SaveConfiguration(@"C:\config.xml");
dgvInstance.LoadConfiguration(@"C:\config.xml");

Description

Two methods that extends DataGridView control to save and load columns configuration to specified XML file. More informations (in Polish, example in English) at: http://kozub.net.pl/2012/02/22/datagridview-konfiguracja-kolumn-oraz-zapis-i-odczyt-stanu/ http://kozub.net.pl/2012/03/21/c-extension-methods/

Details

Double click on the code to select all.

 

;