Search code examples
vb.netstringvisual-studio-2012listboxitems

How can I save listbox items into a string


I want to save all the items I have in my listbox into a string in this kind of format.

String = listboxitem1,listboxitem2,listboxitem3,listboxitem4,listboxitem5....

So then later once I want to pull them back up I can use a breaker and break it up, then load them into listbox1 again. I have a rough idea how to do this but not sure. I was thinking save 1 item in listbox1 at a time then separate them with "," then put it in the string. I have no idea how to put that in code though.

SOLUTION!

Found that the solution was I load it into a listbox, then I added this code

For Each Item As Object In ListBox1.Items
                [StringNameHere!] &= (Item & ",")
Next

Then I load the string by splitting the string between every ","


Solution

  • I understand you have solved your own question. Just an additional suggestion for you if it is not a must for you to store your data as string. What if the value in your ListBox contains a "," ? It will give you another row since you are spliting it with a "," in the later part.

    Try using the below:

    To Store the value from ListBox:

     Dim itemListToStore As New List(Of ListItem)
     For Each item As ListItem In ListBox1.Items
         itemListToStore.Add(item)
     Next
    

    To populate the ListBox with stored value:

     For Each pullOutItem As ListItem In itemListToStore
         ListBox1.Items.Add(pullOutItem.Text)
     Next
    

    This will overcome the problem of delimiter.