arraysvb.netmy.settings

How can I store an array in my.settings in vb.net


I am trying to store a user input array in a my.settings variable in vb.net. I would like for the user to enter an array in the form {1,2,3}, store that as a string in the setting and then be able to use the setting value later to create a new array. The code will be something like:

Dim inputarray()
Dim outputarray()

inputarray=textbox1.text
my.settings.inputstoredarray.add(inputarray)

outputarray=my.settings.inputstoredarray
textbox2.text=outputarray(0)

'If the user types "{1,2,3}' in textbox1, textbox2 should show "1"

I have tried multiple versions of this but there seem to always be type conversion errors. I don't understand why it works if I hardcode:

inputarray={1,2,3}

and yet the below code does not work:

inputarray=my.settings.inputstoredarray

How can I store a user provided array in my.settings and retrieve it for use later?

does not work even if I go into settings and set the string value for the setting to {1,2,3}


Solution

  • Set up your setting in Project Properties, Settings tab as follows. enter image description here

    Then save the setting as follows.

    Private Sub SaveStringToSettings()
        My.Settings.StringOfInts = TextBox1.Text 'User types in {1, 2, 3}
    End Sub
    

    To retrieve the setting and turn it into an array

    Private Sub CreateArrayFromSettings()
        Dim SettingValue = My.Settings.StringOfInts
        Debug.Print(SettingValue) 'View this in the Immediate window
        'Get rid of the braces
        Dim TrimmedString = SettingValue.Trim({"{"c, "}"c})
        'Split the string by the commas into an array 
        Dim Splits = TrimmedString.Split(","c)
        'Get rid of the spaces
        For i = 0 To Splits.Length - 1
            Splits(i) = Splits(i).Trim
        Next
        TextBox1.Text = Splits(0) 'Displays 1
    End Sub