[英]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对象,该对象已添加到用户范围中的项目设置中(应用程序范围中的设置不能直接更新),您可以使用BindingSource处理您的字符串集合。
此类可以将其内部列表绑定到几乎任何集合,并且对其内部列表的任何更改都反映在绑定到它的集合中。
这当然包括从集合中添加和删除项目。
注意:在这里,您的listboxitems
设置被重命名为ListBoxItems
(使用适当的大小写)
listBox5
在listBox5
中发生了someListBox
(➨ 建议为您的 Controls 赋予有意义的名称)。
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属性返回所选项目的索引。
按降序对索引进行排序(删除项目而不修改索引序列)并使用BindingSource.RemoveAt()方法删除每个选定的项目。
如果只有一个选定的 Item 并且使用 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();
我想在列表框中添加多个文件
//Add Files in Listbox private void button57_Click(object sender, EventArgs e) { FolderBrowserDialog dialog = new FolderBrowserDialog(); dialog.Description = "Please select the directory that includes images"; if (dialog.ShowDialog() == DialogResult.OK) { string folderName = dialog.SelectedPath; string s = Path.GetFileName(folderName); listboxsource.Add(s); Properties.Settings.Default.Save(); } }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.