如何将列表框项保存到项目设置


private void Form1_Load(object sender, EventArgs e)
{
var newList = Properties.Settings.Default.listboxitems;
foreach (object item in listBox5.Items)
{
newList.Add(item);
listBox5.Items.Add(item);
}
}
private void button57_Click(object sender, EventArgs e)
{
string s = Path.GetFileName(folderName);
listBox5.Items.Add(s);
var newList = new ArrayList();
foreach (object item in listBox5.Items)
{
newList.Add(item);
}
Properties.Settings.Default.listboxitems = newList;
Properties.Settings.Default.Save();
}

我想在列表框中添加文件夹并保存在设置中,这些项目在FormLoad/?中加载??可以在Form Load中加载项目吗?提前感谢!

假设您的listboxitems是添加到"用户"作用域中的"项目设置"中的StringCollection对象("应用程序"作用域的设置无法直接更新(,则可以使用BindingSource处理您的字符串集合
此类可以将其内部列表绑定到几乎任何集合,对其内部列表的任何更改都会反映在绑定到它的集合中。
这当然包括添加和删除集合中的项目。

注意:此处,您的listboxitems设置已重命名为ListBoxItems(使用适当的大小写(
listBox5someListBox中已更改(➨建议给控件起有意义的名称(。

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;
}

现在,要将新的Item添加到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();

若要从集合中删除Items,当数据显示在ListBox中时,您可能需要考虑ListBox SelectionMode
如果不是SelectionMode.One,则必须处理多个选择:SelectedIndices属性返回所选项目的索引
按降序排列索引(在不修改索引序列的情况下删除项(,并使用BindingSource.RemoveAt((方法删除每个选定项。

如果只有一个选定的项,并且使用ListBox执行选择,则可以使用BindingSource.RemoveCurrent((方法
如果需要通过其他方式(例如TextBox(删除中指定的字符串,则需要使用BindingSource.remove((方法删除字符串本身。请注意,is将只删除第一个匹配的字符串。

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();

最新更新