Last active
September 26, 2022 06:41
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <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