从列表框保存到c#Win Form中的.csv文件 [英] Saving from a list box to a .csv file in c# Win Form
问题描述
我已经研究了好几个小时了,我认为最好的主意是为每个循环提出一个,然后将其传递给Stream Writer.
I have been looking around for hours on how to do this, I think the best idea is to come up with a for each loop and then pass that through into the Stream Writer.
我已经尝试了多种不同的方法,并且我认为也许我还不足以看到我的错误,如果有人能够提供帮助的话,那就太好了.
I've tried multiple different ways, and I think maybe I'm just not good enough to see my error, if anyone would be able to help that's be great.
当前已创建文件,并且我得到的唯一输出是第一行上的"System.Windows.Forms.ListBox + ObjectCollection",这向我暗示我没有正确地传递值.
Currently the file gets created and the only output I get for it is "System.Windows.Forms.ListBox+ObjectCollection" on the first line, which suggests to me that I'm not passing the values out properly.
这是代码:
private void btnSave_Click(object sender, EventArgs e)
{
StreamWriter myOutputStream = new StreamWriter("Myfile.csv");
myOutputStream.WriteLine(lstBox.Items);
myOutputStream.Close();
//foreach (object item in lstBox.Items)
//string listString = lstBox.SelectedItem.ToString();
//StreamWriter streamBox = File.CreateText(@"testfile.csv");
//streamBox.Write(listString);
//streamBox.Close();
//if (SaveFileDialog.ShowDialog() == DialogResult.OK)
//{
// System.IO.StreamWriter streamBox = new System.IO.StreamWriter(SaveFileDialog);
// foreach (object item in lstBox.Items)
// streamBox.WriteLine(item.ToString());
// streamBox.Close();
//}
}
所有注释掉的部分都是我过去尝试过的东西.但是现在,我认为最简单的方法是前三行.
All the commented out parts are things I've tried in the past. But right now, I think the simplest way was the top three lines.
感谢您的输入.
推荐答案
您正在写出listBox.Items
,它是ListBoxObjectCollection
.您需要一个foreach循环来编写每个项目:
You are writing out listBox.Items
, which is an ListBoxObjectCollection
. You need a foreach loop to write each item:
StreamWriter myOutputStream = new StreamWriter("Myfile.csv");
foreach (var item in lstBox.Items)
{
myOutputStream.WriteLine(item.ToString());
}
myOutputStream.Close();
还请注意,您可以在此处使用using
块:
Also note that you can use a using
block here:
using (StreamWriter myOutputStream = new StreamWriter("Myfile.csv"))
{
foreach (var item in lstBox.Items)
{
myOutputStream.WriteLine(item.ToString());
}
}
这篇关于从列表框保存到c#Win Form中的.csv文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!