【发布时间】:2018-05-05 00:43:11
【问题描述】:
我不想将列表框项目保存到文本文件中,而是保存它们,以便在将项目添加到列表框并关闭应用程序时,在打开应用程序时,添加到列表框的项目仍然存在。
用例:
- 用户打开应用程序。
- 用户使用按钮将名为“项目 1”的项目添加到列表框中。
- 用户关闭应用程序。
- 用户再次打开应用程序,发现“项目 1”仍在列表框中,并且添加的项目并未因应用程序关闭而丢失。
我已经看到人们成功地使用文本框数据(例如此视频:saving user settings)执行此类操作,但无法使其与列表框数据一起使用。
以下是我尝试根据链接的视频自己执行此操作的方法,该视频从用户用于将项目添加到列表框的按钮开始:
private void AddTeamButton_Click(object sender, EventArgs e)
{
// add the item to the listbox
listBox1.Items.Add("Example string);
// add the item to the ListBoxStuff settings
Settings.Default["ListBoxStuff"] = Settings.Default["ListBoxStuff"] + "|" + "Example string";
}
然后在表单加载时:
private void Form1_Load(object sender, EventArgs e) // needs to stay
{
// Items from the ListBoxStuff setting is saved as a string - this may be the issue, but am unsure, this gets the values of the settings?
string listboxItems = Settings.Default["ListBoxStuff"].ToString();
// If there are values other than null or empty.
if (listboxItems != null || !listboxItems.Equals(""))
{
string[] separators = { "|" };
// Put the items in a string array, splitting them at the | which means the next item in the string
string[] itemsToAdd = listboxItems.Split(separators, StringSplitOptions.RemoveEmptyEntries);
// Loop through the array
foreach (string i in itemsToAdd)
{
// Add each item to the list box
listBox1.Items.Add(i);
}
}
}
我的想法是,每次用户将项目添加到列表时,listboxstuff 字符串都会使用 | 添加项目。在这中间,在加载时,我们得到这个字符串,在每个 | 处拆分它,并将新创建的数组中的每个项目添加到列表框中,如果它是空的,则没有任何反应。
但结果是添加项目后重新打开应用程序时添加到列表框中的项目不存在。
有谁知道如何做到这一点?
【问题讨论】: