vb.netsettings.settings

How can I save listbox items to my.settings


Intro

I have looked up how to save the items in a listbox to my.settings for a while now and there are so many different answers. I've tried them all (a bit excessively to say), but none have really worked. Its probably because I'm doing something wrong due to a bad explanation or my new-beginner stage at programming.

So I have a form where the user can set a bunch of settings. All of them are going to stay the way they were when he closes the application and re-opens it again. Textboxes, checkboxes and so on works fine, but for some reason the Listbox is harder than I'd expect to be saved.

My listbox

The user adds items to the listbox like this (Writes something like c:\test in a textbox tbpath1, presses a button btnAdd1 and the text will become a item in the listbox lbchannel1)

Private Sub btnAdd1_Click(sender As Object, e As EventArgs) Handles btnAdd1.Click
    Dim str As String = tbPath1.Text
    If str.Contains("\") Then
        lbchannel1.Items.AddRange(tbPath1.Text.Split(vbNewLine))
        tbext1_1.Text = (tbext1_1.Text)

My attempt (probably one out of ten attempts)

So this is one of my attempts so far. I wish it was this easy.

enter image description here

My.Settings._lbchannel1.Clear()
For Each item In lbchannel1.Items
    My.Settings._lbchannel1.Add(item)
Next
My.Settings.Save()

At the attempt above, I get error 'NullReferenceException was unhandled : Object reference not set to an object instance'

I'm guessing it has something to do with items not being a string and so on, but I'm not sure where to go with this. Can someone wrap it up in a simple explained way?


Solution

  • If you do not add at least one item in the IDE, VS doesnt initialize the collection you create in Settings because it doesnt look like you are using it.

    If My.Settings._lbchannel1 Is Nothing Then
        My.Settings._lbchannel1 = New System.Collections.Specialized.StringCollection()
    End If
    
    My.Settings._lbchannel1.Clear()
    For Each item In lbchannel1.Items
        My.Settings._lbchannel1.Add(item)
    Next
    My.Settings.Save()
    

    You can also "trick" it into initializing it for you. Add an item via the Settings Tab, save the project, then remove the item.

    You can also create a List(of String) to store the data. Serialize it yourself with 1-2 lines of code and use it as the DataSource for the listbox. It is simpler than shuttling items from one collection to another and keeping them in synch. This answer shows a serializing a List(Of Class) but the principle is the same.