假设您的 listboxitems 是添加到用户范围内项目设置中的 StringCollection 对象(不能直接更新应用程序范围内的设置),您可以使用 BindingSource 处理您的字符串集合。
此类可以将其内部列表绑定到几乎任何集合,对其内部列表的任何更改都会反映在与其绑定的集合中。
这当然包括在集合中添加和删除项目。
注意:在这里,您的 listboxitems 设置已重命名为 ListBoxItems(使用正确的大小写)
listBox5 已更改为 someListBox(➨ 建议为您的控件提供有意义的名称)。
using System.Linq;
BindingSource listBoxSource = null;
public Form1()
{
InitializeComponent();
// [...]
// Initialize the BindingSource using the ListBoxItems setting as source
listBoxSource = new BindingSource(Properties.Settings.Default.ListBoxItems, "");
// Set the BindingSource as the source of data of a ListBox
someListBox.DataSource = listBoxSource;
}
现在,要向 ListBox 和 StringCollection 对象(您的 listboxitems 设置)添加一个新项目,只需向 BindingSource 添加一个新字符串:它会自动更新自己的源列表。然后,您可以立即保存设置(例如,如果应用程序突然终止,以防止数据丢失)。或者在任何其他时间执行此操作。
// One item
listBoxSource.Add("New Item");
// Or multiple items
foreach (string item in [Some collection]) {
listBoxSource.Add(item);
}
// Save the Settings if required
Properties.Settings.Default.Save();
要从集合中删除项目,当数据显示在 ListBox 中时,您可能需要考虑 ListBox SelectionMode。
如果不是SelectionMode.One,您将不得不处理多个选择:所选项目的索引由SelectedIndices 属性返回。
以降序排列索引(在不修改索引顺序的情况下删除 Items)并使用BindingSource.RemoveAt() 方法删除每个选定的项目。
如果只有一个选定的项,并且使用列表框执行选择,则可以使用BindingSource.RemoveCurrent() 方法。
如果您需要删除通过其他方式指定的字符串(例如,文本框),则需要使用 BindingSource.Remove() 方法删除字符串本身。请注意,它只会删除第一个匹配的字符串。
if (someListBox.SelectedIndices.Count == 0) return;
if (someListBox.SelectedIndices.Count > 1) {
foreach (int idx in someListBox.SelectedIndices.
OfType<int>().OrderByDescending(id => id).ToArray()) {
listBoxSource.RemoveAt(idx);
}
}
else {
listBoxSource.RemoveCurrent();
}
// Save the Settings if required
Properties.Settings.Default.Save();