Search code examples
vb.netformclosing

How can I save the changes made by the user even when the app closes and restarts?


I have knowledge of the .FormClosing events, but I can't find a way to let the changes made by the user stay there, even when the applications closes completely, and it is re-opened again.

I'm trying to let some string values to remain in the text boxes in which the user entered them. Example:

Public Class PersonalInfo

 Dim Name as String = ""
 Dim LastName as String = ""

    Sub NameAndLastName()
        Name = TextBox1.Text
        LastName = TextBox2.Text
    End Sub


    Private Sub Button1_Click(...) Handles Button1.Click
        NameAndLastName()
        Me.Close()
    End Sub

End Class

So after this closing event, I need that when I re-open the application, the strings to remain in their respective text boxes.


Solution

  • You have to save them somewhere physically (file or database) and retrieve them when Your app start again.

    There is simplest solution saving TextBox values into txt file and retrieve them while starting application.

    Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
            'open new file called saveddata.txt and store each textbox value in new line
            Dim fl As New System.IO.StreamWriter(Application.StartupPath & "\saveddata.txt", False)
            fl.WriteLine(TextBox1.Text)
            fl.WriteLine(TextBox2.Text)
            fl.Close()
        End Sub
    
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            'check if saveddata.txt file exist and, if exist, take values from it and store to textboxes
            If System.IO.File.Exists(Application.StartupPath & "\saveddata.txt") = True Then
                Dim fl As New System.IO.StreamReader(Application.StartupPath & "\saveddata.txt")
                TextBox1.Text = fl.ReadLine
                TextBox2.Text = fl.ReadLine
                fl.Close()
            End If
        End Sub
    

    This is the simplest solution. You can store those values into xml, database... values can be encrypted, and so on.