Saving a list to My.Settings

1.9k Views Asked by At

I am trying to save a list variable to My.Settings, but I cannot find a type that works. I am using Visual Studio 2017. Here is how I built the list...

Dim Parameters As New List(Of String)
Parameters.Add("Item1")
Parameters.Add("Item2")

The error comes up when trying to load or save the setting.

Dim Times As New List(Of String)
Times = My.Settings.Times

or

My.Settings.Item("Times") = Times

though the latter doesn't show up as an error but it crashes the program.

I have tried setting the type of setting to String, StringCollection, ListDictionary, etc. but to no avail.

1

There are 1 best solutions below

0
On BEST ANSWER

A System.Collections.Specialized.StringCollection is the most common one used, although you cannot assign a List(Of String) to it directly as they are different types.

Instead you have to iterate your List(Of String) and add every item to the My.Settings list:

'Remove the old items.
My.Settings.Clear()

'Add the new ones.
For Each Item As String In Times
    My.Settings.Times.Add(Item)
Next

Likewise, when reading it back into the List(Of String):

For Each Item As String In My.Settings.Times
    Times.Add(Item)
Next