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?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

lazyberezovskyCommented:
Lazy solution: use http://converter.telerik.com/ for converting C# code to VB.NET
0
Jorge PaulinoIT 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

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
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
CompTIA Security+

Learn the essential functions of CompTIA Security+, which establishes the core knowledge required of any cybersecurity role and leads professionals into intermediate-level cybersecurity jobs.

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
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Visual Basic.NET

From novice to tech pro — start learning today.