VB.NET Saving / loading listbox
Hi how can i save load a listbox ?
with settings
Not the textfile stuff
I tried this
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
ListBox1.Text = My.Settings.history
Timer开发者_JAVA技巧1.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
but no luck please help
Every WinForms control has a Text
property by virtue of inheriting from Control
. For some controls, like ListBox
, this property is basically useless.
You probably want the items in the ListBox
. So give history
a type of StringCollection
and save/load it like this:
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
'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
精彩评论