Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Save all items in a ListBox to text file

Recently I've been quite enjoying C# and I'm just testing with it but there seems to be one part I don't get.

Basically I want it so that when I click the SAVE button must save all the items in the listbox to a text file. At the moment all it comes up with in the file is System.Windows.Forms.ListBox+ObjectCollection.

Here's what I've got so far. With the SaveFile.WriteLine(listBox1.Items); part I've tried putting many different methods in and I can't seem to figure it out. Also take in mind that in the end product of my program I would like it to read back to that to that text file and output what's in the text file to the listbox, if this isn't possible then my bad, I am new to C# after all ;)

private void btn_Save_Click(object sender, EventArgs e)
{
    const string sPath = "save.txt";

    System.IO.StreamWriter SaveFile = new System.IO.StreamWriter(sPath);
    SaveFile.WriteLine(listBox1.Items);
    SaveFile.ToString();
    SaveFile.Close();

    MessageBox.Show("Programs saved!");
}
like image 208
SirTiggs Avatar asked Dec 15 '13 13:12

SirTiggs


2 Answers

From your code

SaveFile.WriteLine(listBox1.Items);

your program actually does this:

SaveFile.WriteLine(listBox1.Items.ToString());

The .ToString() method of the Items collection returns the type name of the collection (System.Windows.Forms.ListBox+ObjectCollection) as this is the default .ToString() behavior if the method is not overridden.

In order to save the data in a meaningful way, you need to loop trough each item and write it the way you need. Here is an example code, I am assuming your items have the appropriate .ToString() implementation:

System.IO.StreamWriter SaveFile = new System.IO.StreamWriter(sPath);
foreach(var item in listBox1.Items)
{
    SaveFile.WriteLine(item.ToString());
}
like image 137
Ivaylo Slavov Avatar answered Oct 09 '22 17:10

Ivaylo Slavov


Items is a collection, you should iterate through all your items to save them

private void btn_Save_Click(object sender, EventArgs e)
{
    const string sPath = "save.txt";

    System.IO.StreamWriter SaveFile = new System.IO.StreamWriter(sPath);
    foreach (var item in listBox1.Items)
    {
        SaveFile.WriteLine(item);
    }

    SaveFile.Close();

    MessageBox.Show("Programs saved!");
}
like image 38
BRAHIM Kamel Avatar answered Oct 09 '22 15:10

BRAHIM Kamel