保存和返回列表框内容
本文关键字:列表 返回 保存 | 更新日期: 2023-09-27 18:18:16
我有一个关于从列表框中保存内容并将其放入.ini文件的问题。
我还想检索信息,并在程序启动时将其放回列表框中。
我有两个列表框,分别叫它们listBox1
和listBox2
。
还有一个按钮,我们叫它selectbttn
。
当我点击选择按钮时,必须保存listBox2
的内容。br/>我怎样才能解决这个问题?
这是两个列表框的代码,没有选择按钮的代码。您在代码中看到的按钮是一个add按钮,它将内容从listbox1添加到listbox2。
private void add_button_Click(object sender, EventArgs e)
{
try
{
if (list_selected.Items.Contains(List_selection.SelectedItem))
{
MessageBox.Show("Can not add the type twice.");
}
else
{
list_selected.Items.Add(List_selection.SelectedItem);
}
}
catch
{
{
MessageBox.Show("No type selected");
}
}
}
您需要使用StreamWriter
来保存到文件。您可以这样做:
public void SaveFile_Click(object sender, EventArgs e)
{
using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:'YourFile.ini"))
{
foreach (var item in list_selected.Items)
{
file.WriteLine(item.ToString());
}
}
}
http://msdn.microsoft.com/en-us/library/vstudio/8bh11f1k.aspx 您可以在应用程序加载时使用StreamReader
回读.ini文件的内容。我将把这个问题留给您,因为您最初没有提供代码。
Write
File.WriteAllLines("test.ini",
listbox.Items.Cast<ListItem>().Select(i => i.Text).ToArray());
负载 listbox.Items.AddRange(File.ReadAllLines("test.ini")
.Select(l => new ListItem(l)).ToArray());