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

How to save Listbox Items to Project settings

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 object added to the Project's Settings in the User scope (settings in the Application scope cannot be updated direcly), you can use a BindingSource 处理您的字符串集合。
此 class 可以将其内部列表绑定到几乎任何集合,并且对其内部列表的任何更改都会反映在与其绑定的集合中。
这当然包括在集合中添加和删除项目。

注意:此处,您的 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;
}

现在,要将新项目添加到 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, you'll have to handle multiple selections: the indices of the selected Items is returned by the SelectedIndices 属性.
按降序排列索引(在不修改索引序列的情况下删除项目)并使用 BindingSource.RemoveAt() 方法删除每个选定的项目。

如果只有一个选中的项目,并且使用列表框进行选择,则可以使用BindingSource.RemoveCurrent()方法。
如果您需要通过其他方式(例如 TextBox)删除指定的字符串,则需要使用 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();