2011-08-04 31 views
0

嗨如何保存加載列表框?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 

,但沒有運氣,請幫助

+0

你想保存整個列表或只是所選擇的項目? –

回答

5

每一個的WinForms控制憑藉從Control繼承的有Text屬性。對於一些控件,如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 
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 
+1

哇!看起來像過量殺菌:( –