Saving Column arrangements datagridview to a user config file

vb.net 2008
I'm loading a datagrid via oledataadapter..

When a user changes column arrangements, they need to be able to save the arrangements and so th next time they open the form and user uses  the  datagrid, the column arrangements need to be the same as they changed them...

I have found c# code...but no vb.net code...
or examples?

Thanks
fordraiders

 
LVL 3
FordraidersAsked:
Who is Participating?
 
Jorge PaulinoConnect With a Mentor IT Pro/DeveloperCommented:
Here you have a small example:
PS: Don't forget to create a new setting "dgvColumnWidth"

    ''' <summary>
    ''' Saves the actual column width
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub DataGridView1_ColumnWidthChanged(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewColumnEventArgs) Handles DataGridView1.ColumnWidthChanged

        ' Gets the current width
        Dim columnWidth As String = String.Empty
        For Each col As DataGridViewColumn In Me.DataGridView1.Columns
            columnWidth &= col.Width & ";"
        Next
        columnWidth = columnWidth.Remove(columnWidth.Length - 1)

        ' Saves it into the setting
        My.Settings.dgvColumnWidth = columnWidth
        My.Settings.Save()

    End Sub


    ''' <summary>
    ''' Apply the saved settings after fill the grid
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub Form1_Shown(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Shown

        If My.Settings.dgvColumnWidth <> String.Empty Then

            Dim x As Integer
            For Each col As String In My.Settings.dgvColumnWidth.Split(";"c)
                Me.DataGridView1.Columns(x).Width = col
                x += 1
            Next

        End If
    End Sub

Open in new window

0
 
lazyberezovskyCommented:
Lazy solution: use http://converter.telerik.com/ for converting C# code to VB.NET
0
 
FordraidersAuthor Commented:
jpaulino, Will this work if the datagridview is unbound ?
I'm loading data as the form loads from code not bound to a tableadapter object.
0
Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

 
Jorge PaulinoIT Pro/DeveloperCommented:
Yes it will. You just need to have always the same number of columns and apply the old settings after fill the grid.
0
 
FordraidersAuthor Commented:
ok...will give it a shot  !
0
 
FordraidersAuthor Commented:
Don't forget to create a new setting "dgvColumnWidth"
 ??

Create a new setting ?

0
 
Jorge PaulinoIT Pro/DeveloperCommented:
No, create a new setting.
My Prject - Settings Tab and then add a new one with the name dgvColumnWidth, Type String, Scope User
0
 
FordraidersAuthor Commented:
jpauline...
Ok, I just noticed something.. What if they change the position of the columns?
0
 
FordraidersAuthor Commented:
ok...thanks ...found the settings.settings...
0
 
FordraidersAuthor Commented:
using the code above:  error message when tryin to get back into the form
Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index

System.ArgumentOutOfRangeException was unhandled
  Message="Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index"
  ParamName="index"
  Source="mscorlib"
  StackTrace:
       at System.Collections.ArrayList.get_Item(Int32 index)
       at System.Windows.Forms.DataGridViewColumnCollection.get_Item(Int32 index)
       at Crs_Enterprise.frmiCart.frmiCart_Shown(Object sender, EventArgs e) in C:\Program Files\Crs Enterprise\Crs Enterprise\Crs Enterprise\frmiCart.vb:line 969
       at System.Windows.Forms.Form.OnShown(EventArgs e)
       at System.Windows.Forms.Form.CallShownEvent()
       at System.Windows.Forms.Control.InvokeMarshaledCallbackDo(ThreadMethodEntry tme)
       at System.Windows.Forms.Control.InvokeMarshaledCallbackHelper(Object obj)
       at System.Threading.ExecutionContext.runTryCode(Object userData)
       at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData)
       at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Windows.Forms.Control.InvokeMarshaledCallback(ThreadMethodEntry tme)
       at System.Windows.Forms.Control.InvokeMarshaledCallbacks()
       at System.Windows.Forms.Control.WndProc(Message& m)
       at System.Windows.Forms.ScrollableControl.WndProc(Message& m)
       at System.Windows.Forms.ContainerControl.WndProc(Message& m)
       at System.Windows.Forms.Form.WndProc(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
       at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
       at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
       at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.Run(ApplicationContext context)
       at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.OnRun()
       at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.DoApplicationModel()
       at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.Run(String[] commandLine)
       at Crs_Enterprise.My.MyApplication.Main(String[] Args) in 17d14f5c-a337-4978-8281-53493378c1071.vb:line 81
       at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
       at System.AppDomain.nExecuteAssembly(Assembly assembly, String[] args)
       at System.Runtime.Hosting.ManifestRunner.Run(Boolean checkAptModel)
       at System.Runtime.Hosting.ManifestRunner.ExecuteAsAssembly()
       at System.Runtime.Hosting.ApplicationActivator.CreateInstance(ActivationContext activationContext, String[] activationCustomData)
       at System.Runtime.Hosting.ApplicationActivator.CreateInstance(ActivationContext activationContext)
       at System.Activator.CreateInstance(ActivationContext activationContext)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssemblyDebugInZone()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException:
0
 
Jorge PaulinoIT Pro/DeveloperCommented:
>> Ok, I just noticed something.. What if they change the position of the columns?
You can save the same of the column and the size of the column in the setting.
>> using the code above:  error message when tryin to get back into the form
You have to show the code in here
0
 
FordraidersAuthor Commented:
its the same as what you posted:
I just named my setting.settings  to "ColumnOrders"
Settings Tab "ColumnOrders"", Type String, Scope User

Private Sub DataGridView1_ColumnWidthChanged(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewColumnEventArgs) Handles DataGridView1.ColumnWidthChanged
        ' Gets the current width
        Dim columnWidth As String = String.Empty
        For Each col As DataGridViewColumn In Me.DataGridView1.Columns
            columnWidth &= col.Width & ";"
        Next
        columnWidth = columnWidth.Remove(columnWidth.Length - 1)
        ' Saves it into the setting
        My.Settings.ColumnOrders = columnWidth
        My.Settings.Save()

    End Sub


Private Sub frmiCart_Shown(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Shown
        If My.Settings.ColumnOrders <> String.Empty Then
            Dim x As Integer
            For Each col As String In My.Settings.ColumnOrders.Split(";"c)
                Me.DataGridView1.Columns(x).Width = col
                x += 1
            Next

        End If

    End Sub

Open in new window

0
 
FordraidersAuthor Commented:
the error was here


Private Sub frmiCart_Shown(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Shown
        If My.Settings.ColumnOrders <> String.Empty Then
            Dim x As Integer
            For Each col As String In My.Settings.ColumnOrders.Split(";"c)
                Me.DataGridView1.Columns(x).Width = col   '  <----------    ERROR HERE
                x += 1
            Next

        End If

    End Sub




Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index
0
 
FordraidersAuthor Commented:
jpaulino, Working great...I out the code in the ketpressdown event, because the grid is unbound. If I oad the code before the dataview is shown, the code does not work. The grid does not actually get loaded with data until on keypress event on a textbox.. If the "Enter" key is pressed.

I guess I can apply this code to other datagridviews on the form ?.  I have 2 others.

Thanks
fordraiders
0
 
Jorge PaulinoIT Pro/DeveloperCommented:
Yes, you can apply to other! It's the same procedure.
0
 
FordraidersAuthor Commented:
ok great  thanks alot !

0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.