【问题标题】:How can I save the changes made by the user even when the app closes and restarts?即使应用程序关闭并重新启动,如何保存用户所做的更改?
【发布时间】:2017-01-15 08:59:17
【问题描述】:

我知道 .FormClosing 事件,但我找不到让用户所做的更改保留在那里的方法,即使应用程序完全关闭并重新打开也是如此。

我试图让一些字符串值保留在用户输入它们的文本框中。示例:

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

所以在这个关闭事件之后,我需要在我重新打开应用程序时,将字符串保留在各自的文本框中。

【问题讨论】:

  • 你不能这样做,因为那是运行时。查看 my.settings,您可以将内容保存在那里以满足您的需要。 SO上有很多答案可以解释这一点。如果要保存更多数据,您需要使用数据库或将其写入文件。

标签: vb.net formclosing


【解决方案1】:

您必须将它们保存在物理位置(文件或数据库)并在您的应用重新启动时检索它们。

最简单解决方案将TextBox 值保存到txt 文件中,并在启动应用程序时检索它们。

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

这是最简单的解决方案。您可以将这些值存储到 xml、数据库中……值可以加密等等。

【讨论】:

  • 只是一个建议,将您的StreamWritersStreamReaders 包装在using 块中,然后对象将关闭并且也被处理掉。还有 Path.Combine 而不是仅仅为路径连接字符串。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-09
  • 1970-01-01
  • 2019-06-27
  • 2018-12-06
  • 2011-08-10
  • 2011-10-29
相关资源
最近更新 更多