Click here to Skip to main content
11,704,473 members (51,082 online)
Click here to Skip to main content

DataGridView that Saves Column Order, Width and Visibility to user.config

, 29 Jul 2009 CPOL 66K 4.2K 67
Rate this:
Please Sign up or sign in to vote.
Enhanced DataGridView that saves column order, width and visibility to user.config
gfoidl.DataGridView0.jpg

Introduction

The DataGridView shipped with the framework allows the user to reorder the columns but there is nothing to persist the new column order.

In this article, I'll show an enhanced DataGridView that saves:

  • column order
  • column width
  • column visibility

to the user.config without the need to code something in the hosting form.

Background 

Usually the application and user-settings are created via the designer in Visual Studio. Behind the scenes, the designer generates code for accessing the settings.

For this control, the code for accessing the settings is generated manually so it's possible to use more advanced datatypes than the few primitive ones provided in the designer.

Because it is possible to have more than one DGV in the client application the settings are stored with the use of a dictionary. The key of the dictionary is the name of the control.

Binary serialization is used because the dictionary implements the IDictionary interface and thus it is not possible to use XML serialization. But this doesn't matter - the result is the same. The only difference is that the information in the user.config is not as readable as with XML serialization.

In .NET assemblies are loaded into an AppDomain and executed from there. Each AppDomain has one configuration-file (not necessarily) and therefore the data of several configuration classes get serialized into this config-file (or read from).

Using the Control 

The usage of the control is not different from the System.Windows.Form.DataGridView.

The Code of the Control

The control is derived from the System.Windows.Form.DataGridView. So everything the DataGridView provides can be provided by this control too.

Attributes of the Class

[Description("Extension of the System.Windows.Forms.DataGridView")]
[ToolboxBitmap(typeof(System.Windows.Forms.DataGridView))]
public class gfDataGridView : System.Windows.Forms.DataGridView
{
    ...
}

The attributes are used for displaying a bitmap and a description of the control in the toolbox - like usual controls do.

Saving the Column Order, Width and Visibility

This is done in the Dispose method. For storing the data, the ColumnOrderItem class is used (see later in this article).

protected override void Dispose(bool disposing)
{
	SaveColumnOrder();
	base.Dispose(disposing);
}

private void SaveColumnOrder()
{
	if (this.AllowUserToOrderColumns)
	{
		List<ColumnOrderItem> columnOrder = new List<ColumnOrderItem>();
		DataGridViewColumnCollection columns = this.Columns;
		for (int i = 0; i < columns.Count; i++)
		{
			columnOrder.Add(new ColumnOrderItem
			{
				ColumnIndex = i,
				DisplayIndex = columns[i].DisplayIndex,
				Visible = columns[i].Visible,
				Width = columns[i].Width
			});
		}

		gfDataGridViewSetting.Default.ColumnOrder[this.Name] = columnOrder;
		gfDataGridViewSetting.Default.Save();
	}
}

At first step, it gets checked whether AllowUserToOrderColumns is enabled or not. If not, there is no necessity to save the column order. This can be omitted if you want to save the width, etc. of the columns.

Then a List is populated with the values that should be saved to user.config and this list gets added or updated to the dictionary where the key is the name of the control. The dictionary gets assigned to the property setting and saved - just like "normal" designer generated settings.

Restoring the Column Order

In the OnCreateControl method the column order gets restored. It's important to start with the first displayed column to get the desired result. If this would be done using the column index, then it's just like dragging a column from one position to another which rearranges the order and the result is wrong.

protected override void OnCreateControl()
{
	base.OnCreateControl();
	SetColumnOrder();
}

private void SetColumnOrder()
{
	if (!gfDataGridViewSetting.Default.ColumnOrder.ContainsKey(this.Name))
		return;

	List<ColumnOrderItem> columnOrder =
		gfDataGridViewSetting.Default.ColumnOrder[this.Name];

	if (columnOrder != null)
	{
		var sorted = columnOrder.OrderBy(i => i.DisplayIndex);
		foreach (var item in sorted)
		{
			this.Columns[item.ColumnIndex].DisplayIndex =
                                item.DisplayIndex;
			this.Columns[item.ColumnIndex].Visible = item.Visible;
			this.Columns[item.ColumnIndex].Width = item.Width;
		}
	}
}

ColumnOrderItem

The items of the list are defined within this class: 

[Serializable]
public sealed class ColumnOrderItem
{
	public int DisplayIndex { get; set; }
	public int Width { get; set; }
	public bool Visible { get; set; }
	public int ColumnIndex { get; set; }
}

Settings

As mentioned earlier in this article, the designer generates usually the code for the settings-class. Here this is done manually and for storing the column order, a Dictionary<string, List<ColumnOrderItem>> is used. This dictionary gets serialized as binary.

internal sealed class gfDataGridViewSetting : ApplicationSettingsBase
{
	private static gfDataGridViewSetting _defaultInstace =
		(gfDataGridViewSetting)ApplicationSettingsBase
		.Synchronized(new gfDataGridViewSetting());
	//---------------------------------------------------------------------
	public static gfDataGridViewSetting Default
	{
		get { return _defaultInstace; }
	}
	//---------------------------------------------------------------------
	// Because there can be more than one DGV in the user-application
	// a dictionary is used to save the settings for this DGV.
	// As key the name of the control is used.
	[UserScopedSetting]
	[SettingsSerializeAs(SettingsSerializeAs.Binary)]
	[DefaultSettingValue("")]
	public Dictionary<string, List<ColumnOrderItem>> ColumnOrder
	{
		get { return this["ColumnOrder"] as Dictionary<string,
                       List<ColumnOrderItem>>; }
		set { this["ColumnOrder"] = value; }
	}
}

The upper part is just the singleton implementation of the settings class. Then the dictionary for storing the column order is defined. The attributes specify that the property:

  • should be stored to the user scope (user.config)
  • serialization mode: binary
  • and the default value is an empty string, i.e. an empty dictionary

That's everything needed.

History

  • 29th July 2009 (Version 1.0.1.1)
    Updated article and code.
    • The problem of having more than one DGV in the client application is solved (due the use of the dictionary).
    • The DGV can be used in several containers (due to setting the columnorder in the OnCreateControl method and due to saving the columnorder in theDispose method.
  • 8th June 2009 (Version 1.0.0.0)
    Initial release.

License

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

Share

About the Author

Günther M. FOIDL
Software Developer (Senior) Foidl Günther
Austria Austria
Engineer in combustion engine development.
Programming languages: C#, FORTRAN 95, Matlab

FIS-overall worldcup winner in Speedski (Downhill) 2008/09 and 2009/10.

You may also be interested in...

Comments and Discussions

 
GeneralMy vote of 4 Pin
J3ssy Pmntra15-Sep-14 8:13
memberJ3ssy Pmntra15-Sep-14 8:13 
SuggestionUnhandled error with runtime populated grid Pin
Member 1056032130-Jan-14 18:16
memberMember 1056032130-Jan-14 18:16 
QuestionGreat post, exactly what I needed but some fixes needed Pin
Dudi Avrahamov16-Dec-13 1:03
memberDudi Avrahamov16-Dec-13 1:03 
QuestionAn easier way to order columns Pin
Member 103092311-Oct-13 6:14
memberMember 103092311-Oct-13 6:14 
Questionthe second Datagrid Pin
C# learning user10-Apr-13 6:28
memberC# learning user10-Apr-13 6:28 
GeneralThanks, plus a VB version, plus an enhancement to accommodate column changes Pin
miteleda12-Nov-12 18:51
membermiteleda12-Nov-12 18:51 
GeneralRe: Thanks, plus a VB version, plus an enhancement to accommodate column changes Pin
Rob Sherratt24-Feb-13 1:59
memberRob Sherratt24-Feb-13 1:59 
SuggestionSome error in VB Version Pin
Member 103741914-Nov-13 20:07
memberMember 103741914-Nov-13 20:07 
QuestionOriginal columns' order Pin
esb771-Oct-12 9:26
memberesb771-Oct-12 9:26 
QuestionThanks Pin
Jafari Sitakange Muganzi28-Aug-12 2:51
memberJafari Sitakange Muganzi28-Aug-12 2:51 
GeneralMy vote of 5 Pin
manoj kumar choubey26-Feb-12 21:30
membermanoj kumar choubey26-Feb-12 21:30 
QuestionThank You Pin
DougDeBug23-Nov-11 6:19
memberDougDeBug23-Nov-11 6:19 
Questionto XML Pin
Member 282837618-Mar-10 4:34
memberMember 282837618-Mar-10 4:34 
AnswerRe: to XML Pin
Günther M. FOIDL3-May-10 22:20
memberGünther M. FOIDL3-May-10 22:20 
GeneralRe: to XML Pin
vlad kg11-May-10 6:43
membervlad kg11-May-10 6:43 
GeneralThank You Pin
harshamn4-Feb-10 4:47
memberharshamn4-Feb-10 4:47 
GeneralRe: Thank You Pin
Günther M. FOIDL3-May-10 22:14
memberGünther M. FOIDL3-May-10 22:14 
GeneralThank You Pin
beattyrd10-Nov-09 8:34
memberbeattyrd10-Nov-09 8:34 
GeneralRe: Thank You Pin
Günther M. FOIDL3-Dec-09 10:43
memberGünther M. FOIDL3-Dec-09 10:43 
Generaldatagridview column with problem Pin
ss_hellhound27-Aug-09 15:55
memberss_hellhound27-Aug-09 15:55 
GeneralRe: datagridview column with problem Pin
Günther M. FOIDL28-Aug-09 13:19
memberGünther M. FOIDL28-Aug-09 13:19 
GeneralRe: datagridview column with problem Pin
ss_hellhound28-Aug-09 18:36
memberss_hellhound28-Aug-09 18:36 
GeneralWhen control is disabled Pin
jig2920-Jul-09 9:40
memberjig2920-Jul-09 9:40 
GeneralRe: When control is disabled Pin
Günther M. FOIDL28-Jul-09 3:48
memberGünther M. FOIDL28-Jul-09 3:48 
GeneralNo need for code in form Pin
gfoidl9-Jun-09 10:00
membergfoidl9-Jun-09 10:00 
GeneralUseful Pin
Maximilian Korporal8-Jun-09 10:04
memberMaximilian Korporal8-Jun-09 10:04 

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.150819.1 | Last Updated 29 Jul 2009
Article Copyright 2009 by Günther M. FOIDL
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid