保存并加载项目Listview(my.settings)

时间:2018-01-27 10:10:59

标签: vb.net listview

我想确保当我点击按钮时,该应用会将项目保存在ListView中。

Private Sub App_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
My.Settings.ListViewItems = ListView1.Items
My.Settings.Save()
End Sub

你能告诉我整个程序吗? (String或System.Collections.Specialized.StringCollection等...)

1 个答案:

答案 0 :(得分:0)

使用JSON执行此操作,它可以处理任何类型的信息。

要序列化为字符串:

' Define a List
Dim arr As New List(Of String)

' Add to List
For Each item As ListViewItem In Me.ListView1.Items
    arr.Add(item.Text)
Next

' Serialize The Data to Text
My.Settings.ListViewItem = New System.Web.Script.Serialization.JavaScriptSerializer().Serialize(arr.ToArray())

' Save It
My.Settings.Save()

和解码

' Clear The List If Defined
Me.ListView1.Items.Clear()

' Get Your Array Back
Dim arr() As String = New System.Web.Script.Serialization.JavaScriptSerializer().Deserialize(Of String())(My.Settings.ListViewItem)

' Add Items Back to List
For Each arrItem As String In arr
    Me.ListView1.Items.Add(arrItem)
Next

确保添加对以下内容的引用:

System.Runtime.Serialization
System.Web.Extensions (This is OK for Windows Forms)

如果您有子项,您也可以使用2D数组执行类似的过程。

对于2D:

编码

    Dim arr(Me.ListView1.Items.Count - 1)() As String
    For i As Integer = 0 To Me.ListView1.Items.Count - 1
        ReDim arr(i)(Me.ListView1.Items(i).SubItems.Count - 1)
        arr(i)(0) = Me.ListView1.Items(i).Text
        For j As Integer = 1 To Me.ListView1.Items(i).SubItems.Count - 1
            arr(i)(j) = Me.ListView1.Items(i).SubItems(j).Text
            j = j + 1
        Next
    Next
    My.Settings.ListViewItem = New System.Web.Script.Serialization.JavaScriptSerializer().Serialize(arr)

    My.Settings.Save()

解码

    Me.ListView1.Items.Clear()
    Dim arr()() As String = New System.Web.Script.Serialization.JavaScriptSerializer().Deserialize(Of String()())(My.Settings.ListViewItem)
    For i As Integer = 0 To arr.Length - 1

        Dim lvw As New ListViewItem(arr(i)(0))
        For j As Integer = 1 To arr(i).Length - 1
            If Not arr(i)(j) Is Nothing Then
                lvw.SubItems.Add(arr(i)(j))
            End If
        Next
        ListView1.Items.Add(lvw)
    Next