【问题标题】:How to save Listbox Items to Project settings如何将列表框项目保存到项目设置
【发布时间】:2021-09-29 01:57:56
【问题描述】:
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 中加载项目? 提前致谢!

【问题讨论】:

标签: c# .net winforms listbox settings


【解决方案1】:

假设您的 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();

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2016-10-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-26
相关资源
最近更新 更多