0 Replies - 5114 Views - Last Post: 26 January 2018 - 03:09 PM

#1 talkingcommunities   User is offline

  • New D.I.C Head
  • member icon

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 26-January 18

Saving (persist) form data in VB.NET

Posted 26 January 2018 - 03:09 PM

I searched everywhere for an easy way to save all controls of a form. Looked at using INI files, serialization, etc.
Finally I just wrote my own and it worked so well I thought I'd share. I did it for textbox, maskedtextbox, and checkbox controls only, but once you see the code, you should be able to figure out how to add any other control

Create a setting variable called "ControlValues" in

In the Load sub:
        Dim s() As String = My.Settings.ControlValues.Split("&")

        For Each ss In s
            Dim v() As String = ss.Split("=")
            Dim cc As Control = Me.Controls.Item(v(0))
            If (TypeOf cc Is TextBox) Or (TypeOf cc Is MaskedTextBox) Then
                Me.Controls.Item(v(0)).Text = v(1)
            End If

            If (TypeOf cc Is CheckBox) Then
                Dim c As CheckBox = Me.Controls.Item(v(0))
                c.Checked = v(1)
            End If

I'm sure somebody will provide a much more elegant way of splitting the string into pairs and assigning values to the controls, but this works.

In the Closing sub:
    Private Sub Form1_Closing(sender As Object, e As CancelEventArgs) Handles Me.Closing
        Dim ctlsSerialized As String = ""
        Dim cControl As Control
        For Each cControl In Me.Controls
            If ((TypeOf cControl Is TextBox) Or (TypeOf cControl Is MaskedTextBox)) Then
                ctlsSerialized = ctlsSerialized & cControl.Name & "=" & cControl.Text & "&"
            End If
            If (TypeOf cControl Is CheckBox) Then
                Dim cCH As CheckBox
                cCH = cControl
                ctlsSerialized = ctlsSerialized & cControl.Name & "=" & cCH.Checked & "&"
            End If
        Next cControl
        My.Settings.ControlValues = ctlsSerialized

What it does:
When the form closes, it gathers all the controls on the form and creates a single string of paired keys and values and then saves that string to the settings

When the form loads, it takes the string from settings, splits it into keys and values and assigns the text or checked values accordingly.

It makes it dead simple to add as many more controls as you want to the form and have them persist when the user closes the form and reopens it. Hope this helps some people out there.

Is This A Good Question/Topic? 0
  • +

Page 1 of 1