Visual Studio 2019 (vb) - issue with Reading/Writing My.Settings

690 Views Asked by At

I'm just starting to develop and so there are some concepts that are not clear to me, I need you to try to understand what I'm doing wrong.

My goal is to have a series of ComboBoxes that contain some strings, for example a string is this one, the ComboBox is called TYPE:

ComboboxTYPE

I am storing these strings in My.Settings for my convenience and to edit them directly from the app.exe.config file (these information are stored there right?).

I'm using this code

Private Sub AdminPanel_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        For Each item In My.Settings.TYPE
            ComboBoxType.Items.Add(item)
        Next
End Sub

My issue is that, I'm unable to read from My.Settings.TYPE and when I try to write into it with the following code I doesn't find any strings added into My.Settings menu neither into app.exe.config.

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles ButtonTYPEAddValue.Click
        ComboBoxType.Items.Add(TextBoxType.Text)
        ComboBoxType.Text = TextBoxType.Text
        TextBoxType.Clear()
        MsgBox("Item added!")
End Sub

what is wrong?

1

There are 1 best solutions below

5
Rohan Bari On

In your code, it seems like you've used String to add/remove the ComboBoxType items. Follow the steps to achieve your requirement:

In this screenshot, you can see I've set the Type as System.Collection.Specialized.StringCollection to separate each time for future use.

Items Collection

Now, you may use the following code:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    My.Settings.tests.Add(TextBox1.Text)
    My.Settings.Save()
    ComboBox1.Items.Add(TextBox1.Text)
End Sub

Private Sub AdminPanel_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    For Each item In My.Settings.tests
        ComboBox1.Items.Add(item)
    Next
End Sub

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    My.Settings.tests.Remove(TextBox1.Text)
    My.Settings.Save()
    ComboBox1.Items.Remove(TextBox1.Text)
End

It's noticeable that you can change the variable names, they're differ a bit than yours in my code.

Form structure for the code:

Default form

On the MyBase.Load event, all the items containing in My.Settings.tests will be added using For Each loop (benefit of StringCollection).

Working example of the form [adding - removing using My.Settings]:

Adding to menu         Removing from menu

I hope you've got your answer.