如何将Combobox项目保存在我的设置中,并使用文本框显示/编辑
-
25-10-2019 - |
题
我正在尝试执行以下操作:
- 将ComboBox的项目存储在我的设置中(数据类型无关紧要,但需要建议)。
- 检索这些项目以在Formload上填充Combobox。
- 另外,在文本框中显示这些项目(每行1个项目),我可以在其中编辑并将编辑保存到我的settings和combobox中。
我有点迷路了,我应该怎么做?
现有代码:
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
但是,此代码无法正确保存值,也无法在Combobox或Textbox中正确显示它们。
解决方案
您可以为设置使用StringCollection类型,您可能需要代码中的以下导入语句以可用: Imports System.Collections.Specialized
然后,您可以将此StringCollection用作ComboBox的数据源。
编辑: 在您的代码中看到您已经使用StringCollection的代码。好的。现在为什么不这样访问您的设置?
My.Settings.Items = itemCollection
这样,您肯定不会犯打字错误,并且还可以确定自己设置确实存在。您还尝试踏入代码以检查您的设置是否实际保存?
不隶属于 StackOverflow