VB 2013持久用户设置

时间:2014-07-01 19:59:31

标签: vb.net foreach listbox persistent-storage

在我的表单上,我有一个带有"文件保存"的菜单。单击“保存”时,我希望保存特定设置,以便在关闭并重新打开表单时进行还原。我已经成功完成了文本框中的文本和复选框的检查状态,但是当我尝试遍历列表框中的项目时,我失败了。请看下面我尝试过的内容......

点击保存时:

Private Sub SaveToolStripMenuItem_Click(sender As Object, e As EventArgs) 
      Handles SaveToolStripMenuItem.Click
For Each i In ListBox1.Items()
    My.Settings.ListBox1.Add(i)
Next
My.Settings.Save()
End Sub

当我的表单加载时:

Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) 
        Handles Me.Load
For Each i In My.Settings.ListBox1()
    ListBox1.Items.Add(i)
Next
End Sub

我只使用VB三天了,所以如果我错过了简单的哈哈,请道歉!谢谢你的帮助!!!

1 个答案:

答案 0 :(得分:0)

设置中有一个带有StringCollection的小故障。如果你没有使用假变量播种它,那么它从Nothing开始,你不能添加到Nothing。在您的表单加载中添加:

' if the collection has not been initialized, do so
If My.Settings.ListBox1 Is Nothing Then
    My.Settings.ListBox1= New System.Collections.Specialized.StringCollection
End If

' now it is safe to use: load strings from Setting -> form listbox
For Each s As String In My.Settings.ListBox1()
    ListBox1.Items.Add(s)
Next

第一次运行时,可能没有保存设置,因此我们必须为它们创建容器。


Option Strict可以通过文件实现,在顶部添加:

Option Strict On

或者对于项目:Project => Properties => Compile:Option Strict可能是正确的(我有2012年)。您也可以将其设置为永久选项(推荐)。

除此之外,这将阻止您从空中采集变量并在不声明类型( 会导致错误)的情况下使用它们。例如:

For Each i In My.Settings.ListBox1()

变为

For Each s As String In My.Settings.ListBox1()  ' tell the compiler the Type