VB.NET保存/加载列表框

时间:2011-08-04 19:29:38

标签: vb.net

您如何保存列表框?

设置

不是文本文件的东西

我试过这个

   Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    ListBox1.Text = My.Settings.history
    Timer1.Start()
End Sub

Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
    My.Settings.history = ListBox1.Text
    My.Settings.Save()
End Sub

但没有运气请帮助

2 个答案:

答案 0 :(得分:5)

由于继承自Text,每个WinForms控件都具有Control属性。对于某些控件,例如ListBox,此属性基本上没用。

您可能想要ListBox中的。所以给history StringCollection类型并保存/加载它:

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    ' This is in case the history setting isn't initialized. '
    If My.Settings.history IsNot Nothing Then
        For Each item In My.Settings.history
            ListBox1.Items.Add(item)
        Next
    End If
    Timer1.Start()
End Sub

Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
    ' Same reasoning as above. '
    If My.Settings.history Is Nothing Then
        My.Settings.history = new StringCollection
    End If

    My.Settings.history.Clear()
    For Each item In ListBox1.Items
        My.Settings.history.Add(item)
    Next
    My.Settings.Save()
End Sub

答案 1 :(得分:0)

 'create and populate an array, the items collection is not serializable
Dim LBitem As New ArrayList()
For Each itm As ListItem In ListBox1.Items
LBitem.Add(itm.Value)
Next
‘create an XmlSerializer and use it to populate a memory stream
Dim xs As New System.Xml.Serialization.XmlSerializer(GetType(ArrayList))
Dim ms As New System.IO.MemoryStream
Try
xs.Serialize(ms, LBitem)
Catch ex As Exception
End Try

‘rewind the stream
ms.Seek(0, 0)
‘read the stream to string, I use a StreamReader to take advantage of ReadToEnd
Dim sr As New System.IO.StreamReader(ms)
Dim str As String = sr.ReadToEnd
‘now we can save the string to a database
Here is the code that re-populates the list from an XML string

‘we’ll start with a string of xml called str. I’ll assume it’s already pulled from the database
       'To convert a string to a stream  we have to convert to a byte array first.
       'aStr is str converted to an array of bytes
        Dim uniEncoding As New UnicodeEncoding()
        Dim aStr As Byte() = uniEncoding.GetBytes(str)

      'wrtie the byte array to a stream and rewind it

        Dim ms As New System.IO.MemoryStream
        ms.Write(aStr, 0, aStr.Length)
        ms.Seek(0, 0)

      'de-serialize from xml to an array of strings
        Dim LBitem As New ArrayList()
        Dim xs As New System.Xml.Serialization.XmlSerializer(GetType(ArrayList))

        Try
            LBitem = xs.Deserialize(ms)
        Catch ex As Exception
        End Try

      'load the array into the listbox's items collection
        ListBox1.Items.Clear()
        For Each itm As Object In LBitem
            ListBox1.Items.Add(itm.ToString)
        Next