Click here to Skip to main content
15,885,985 members
Articles / Desktop Programming / Windows Forms

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

Rate me:
Please Sign up or sign in to vote.
4.64/5 (19 votes)
29 Jul 2009CPOL3 min read 137.3K   6.9K   75   30
Enhanced DataGridView that saves column order, width and visibility to user.config
gfoidl.DataGridView0.jpg

Image 2

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

C#
[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).

C#
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.

C#
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: 

C#
[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.

C#
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)


Written By
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.

Comments and Discussions

 
GeneralMy vote of 5 Pin
osmanx18-Mar-23 11:09
osmanx18-Mar-23 11:09 
SuggestionMultiple gfDataGridView's with same name Pin
symmetr122-Dec-20 8:32
symmetr122-Dec-20 8:32 
GeneralMy vote of 5 Pin
ClusterM6-Mar-19 21:17
ClusterM6-Mar-19 21:17 
GeneralMy vote of 4 Pin
J3ssy Pmntra15-Sep-14 8:13
J3ssy Pmntra15-Sep-14 8:13 
SuggestionUnhandled error with runtime populated grid Pin
Member 1056032130-Jan-14 18:16
Member 1056032130-Jan-14 18:16 
QuestionGreat post, exactly what I needed but some fixes needed Pin
Dudi Avrahamov16-Dec-13 1:03
Dudi Avrahamov16-Dec-13 1:03 
First of all I would like to thank the author of post. A DataGridView that saves its column width was exactly what I needed.
However, there were some thing I needed to fix in the original code:
1. If you have two DataGridView controls with the same name (in two different forms), the column sizes of one DataGridView will affect the other.
2. If the application doesn't exit but the form which the DataGridView control reside closes, the setting not always saved.

Solutions:
1. Concatenate the parent name with the DataGridView name for the dictionary key.
2. Not use the dispose() for saving the settings but register to the ColumnWidthChanged event instead and save the setting on the event handler function.

C#
public DataGridViewEx()
  {
      this.ColumnWidthChanged += new DataGridViewColumnEventHandler(DataGridViewEx_ColumnWidthChanged);
  }

  void DataGridViewEx_ColumnWidthChanged(object sender, DataGridViewColumnEventArgs e)
  {
      SaveColumnOrder();
  }

  private void SetColumnOrder()
  {
      m_parentName = this.Parent.Name;
      if (!DataGridViewExSetting.Default.ColumnOrder.ContainsKey(m_parentName + this.Name))
          return;

      List<ColumnOrderItem> columnOrder =
          DataGridViewExSetting.Default.ColumnOrder[m_parentName + 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;
          }
      }
  }



Enjoy!
PraiseRe: Great post, exactly what I needed but some fixes needed Pin
DominikP19-Jan-16 18:58
DominikP19-Jan-16 18:58 
QuestionAn easier way to order columns Pin
Member 103092311-Oct-13 6:14
Member 103092311-Oct-13 6:14 
Questionthe second Datagrid Pin
C# learning user10-Apr-13 6:28
C# learning user10-Apr-13 6:28 
GeneralThanks, plus a VB version, plus an enhancement to accommodate column changes Pin
miteleda12-Nov-12 18:51
miteleda12-Nov-12 18:51 
GeneralRe: Thanks, plus a VB version, plus an enhancement to accommodate column changes Pin
Rob Sherratt24-Feb-13 1:59
Rob Sherratt24-Feb-13 1:59 
SuggestionSome error in VB Version Pin
Member 103741914-Nov-13 20:07
Member 103741914-Nov-13 20:07 
QuestionOriginal columns' order Pin
esb771-Oct-12 9:26
esb771-Oct-12 9:26 
QuestionThanks Pin
sitajaf28-Aug-12 2:51
sitajaf28-Aug-12 2:51 
GeneralMy vote of 5 Pin
Manoj Kumar Choubey26-Feb-12 21:30
professionalManoj Kumar Choubey26-Feb-12 21:30 
QuestionThank You Pin
DougDeBug23-Nov-11 6:19
DougDeBug23-Nov-11 6:19 
Questionto XML Pin
vlad kg18-Mar-10 4:34
vlad kg18-Mar-10 4:34 
AnswerRe: to XML Pin
Günther M. FOIDL3-May-10 22:20
Günther M. FOIDL3-May-10 22:20 
GeneralRe: to XML Pin
vlad kg11-May-10 6:43
vlad kg11-May-10 6:43 
GeneralThank You Pin
harshamn4-Feb-10 4:47
harshamn4-Feb-10 4:47 
GeneralRe: Thank You Pin
Günther M. FOIDL3-May-10 22:14
Günther M. FOIDL3-May-10 22:14 
GeneralThank You Pin
Richard Beatty10-Nov-09 8:34
Richard Beatty10-Nov-09 8:34 
GeneralRe: Thank You Pin
Günther M. FOIDL3-Dec-09 10:43
Günther M. FOIDL3-Dec-09 10:43 
Generaldatagridview column with problem Pin
ss_hellhound27-Aug-09 15:55
ss_hellhound27-Aug-09 15:55 
GeneralRe: datagridview column with problem Pin
Günther M. FOIDL28-Aug-09 13:19
Günther M. FOIDL28-Aug-09 13:19 

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.