Question

I'm trying to do the following:

  1. Store items from ComboBox in My.Settings (datatype doesn't matter, but need suggestions).
  2. Retrieve these items to populate a ComboBox on formload.
  3. Also display these items (1 item per line) in TextBox, where I can edit and save the edits to both My.Settings and the ComboBox.

I'm a little lost, how should I go about doing this?

Existing Code:

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        Labels.LoadSettings()

        txtNumOfLabels.Text = Labels.numOfLabels

        cboItem.Items.Clear()
        For Each s As String In Labels.items
            cboItem.Items.Add(s)
        Next

    End Sub

    Public Shared items As New Specialized.StringCollection

    Shared Sub LoadSettings()
            Try
                items = My.Settings("Items")
            Catch ex As Exception
                MsgBox(ex.Message, MsgBoxStyle.Exclamation)
            End Try
        End Sub


 Private Sub Options_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        For Each s As String In Labels.items
            txtItems.AppendText(s + Environment.NewLine)
        Next
    End Sub

 Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click
        Dim itemCollection As New Specialized.StringCollection
        For Each s As String In txtItems.Lines
            itemCollection.Add(s)
        Next

        My.Settings("Items") = itemCollection
        My.Settings.Save()
        Labels.LoadSettings()

        Form1.cboItem.Items.Clear()
        For Each s As String In Labels.items
            Form1.cboItem.Items.Add(s)
        Next

        Me.Close()
    End Sub

But this code won't save the values properly, or display them properly in the combobox or textbox.

Was it helpful?

Solution

You could use a StringCollection type for your setting, you may need the following imports statement in your code for the StringCollection to be available: Imports System.Collections.Specialized

You can then use this StringCollection as the DataSource for the combobox.

Edit: Saw in your code that you already use StringCollection. Good. Now why don't you access your setting like this?

My.Settings.Items = itemCollection

This way you're sure not to make a typing mistake, and you're also sure that you setting actually exists. Also did you try stepping through the code to check if your setting is actually saved or not?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top