Skip to content

Instantly share code, notes, and snippets.

@drewchapin
Last active September 26, 2022 06:41
Show Gist options
  • Save drewchapin/16d81e431f566443ea8c0daa5663da5f to your computer and use it in GitHub Desktop.
Save drewchapin/16d81e431f566443ea8c0daa5663da5f to your computer and use it in GitHub Desktop.
Extension methods to save/load column settings to/from the current user registry for a DataGridView control.
/// <summary>
/// Generate a backslash separated path showing parent\child\grandchild relationship.
/// </summary>
public static string GeneratePath( this Control control )
{
string path = control.Name;
for( Control parent = control.Parent; parent != null; parent = parent.Parent)
path = String.Format("{0}\\{1}",parent.Name,path);
return path;
}
/// <summary>
/// Save datagridview column settings to current user registry
/// </summary>
/// <param name="gridview">DataGridView control to save settings for</param>
public static void SaveColumnSettings( this DataGridView gridview )
{
string basePath = String.Format("Software\\{0}\\{1}\\{2}",Application.CompanyName,Application.ProductName,gridview.GeneratePath());
foreach( DataGridViewColumn column in gridview.Columns )
{
string path = String.Format("{0}\\{1}",basePath,column.Name);
using( Microsoft.Win32.RegistryKey key = Microsoft.Win32.Registry.CurrentUser.CreateSubKey(path) )
{
key.SetValue("Width",column.Width,Microsoft.Win32.RegistryValueKind.DWord);
key.SetValue("DisplayIndex",column.DisplayIndex,Microsoft.Win32.RegistryValueKind.DWord);
}
}
}
/// <summary>
/// Read column settings from registry.
/// </summary>
/// <param name="gridview">DataGridView control to load settings for</param>
public static void LoadColumnSettings( this DataGridView gridview )
{
string basePath = String.Format("Software\\{0}\\{1}\\{2}",Application.CompanyName,Application.ProductName,gridview.GeneratePath());
foreach( DataGridViewColumn column in gridview.Columns )
{
string path = String.Format("{0}\\{1}",basePath,column.Name);
using( Microsoft.Win32.RegistryKey key = Microsoft.Win32.Registry.CurrentUser.CreateSubKey(path) )
{
//int preferredWidth = column.GetPreferredWidth(column.AutoSizeMode,true);
column.Width = (int)key.GetValue("Width",column.Width);
column.DisplayIndex = (int)key.GetValue("DisplayIndex",column.DisplayIndex);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment