Saving from a list box to a .csv file in c# Win Fo

2019-08-29 10:56发布

问题:

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.

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.

Here's the code :

        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.

Thanks for your input.

回答1:

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();

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());
    }
}


回答2:

First, what's in the ListBox? If the items in the list box are just string items, then you could do the following:

StreamWriter myOutputStream = new StreamWriter("Myfile.csv");
foreach (string item in lstBox.Items) {
    myOutputStream.WriteLine(item);
}
myOutputStream.Close();