How to save and load user ordered columns in the datagridview-control?

Hi NG!

First, sorry for my bad EnglishSad

The datagridview-Control enables the user to order columns as he like. But how do I store the order of the columns and how do I set the column-order in the way the user want to?

I searched for a sample about My.Settings in association with the datagridview but I haven't found anything...Sad

Does anyone know how to do it?

[796 byte] By [Macy-Mike] at [2008-2-27]
# 1
Hi,
Well, you could use My.Settings...
I haven't tried this myself but I think it would work...
Try creating a String Setting in the My.Settings Object. eg. view_grid
after user reorders the column, get the current order, put the name of the column (in Order of appearance) in the string and delimit it with ";"

Upon loading the form, get the String Property in My.Settings, split the string with ";" as the delimiter. loop through the array of strings and reorder your columns...

cheers,
Paul June A. Domag

PaulDomag at 2007-8-21 > top of Msdn Tech,Visual Basic,Visual Basic General...
# 2

That is a great suggestion.

Another thing you can do is save the column names in an ArrayList or a List(Of String).

For example:

1) open the settings designer and click on the Settings tab
2) add a named settings called "GridColumnNames", choose ArrayList as the type, save
3) in code you can get at the values like this:



Public Class Form1

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

Me.LoadGridColumns()

End Sub

Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing

Me.SaveGridColumns()

End Sub

Sub LoadGridColumns()

'retrieve names from My.Settings store

If My.Settings.GridColumnNames IsNot Nothing AndAlso My.Settings.GridColumnNames.Count > 0 Then

For Each name As String In My.Settings.GridColumnNames

'add columns from settings

dgv.Columns.Add(name, name)

Next

Else

'initialize columns on first run

Dim newName As String

newName = "Fred " & Now

dgv.Columns.Add(newName, newName)

newName = "Wilma " & Now

dgv.Columns.Add(newName, newName)

End If

End Sub

Sub SaveGridColumns()

'save names

Dim names As New ArrayList

For Each col As DataGridViewColumn In dgv.Columns

names.Add(col.Name)

Next

My.Settings.GridColumnNames = names

My.Settings.Save()

End Sub

End Class



Hope this helps,

Paul Yuknewicz
Visual Basic

PaulYuk_MS at 2007-8-21 > top of Msdn Tech,Visual Basic,Visual Basic General...
# 3
I've tried saving the display index of datagridview columns in an arraylist or stringcollection in my.settings. However, the setting does not persist between instances of the application, i.e., when I close and reopen the application, the arraylist empties somehow. Does anybody know why? Also, why we can't save settings as simple multi-dimensional arrays?
toneho at 2007-8-21 > top of Msdn Tech,Visual Basic,Visual Basic General...