SirTiggs
SirTiggs

Reputation: 105

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!");
}

Upvotes: 9

Views: 56491

Answers (3)

Tahir Creole
Tahir Creole

Reputation: 41

There is one line solution to the problem.

System.IO.File.WriteAllLines(path, Listbox.Items.Cast<string>().ToArray());

put your file path+name and Listbox name in above code.

Example: in Example below path and name of the file is D:\sku3.txt and list box name is lb System.IO.File.WriteAllLines(@"D:\sku3.txt", lb.Items.Cast<string>().ToArray());

Upvotes: 4

stackh34p
stackh34p

Reputation: 9009

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

Upvotes: 11

BRAHIM Kamel
BRAHIM Kamel

Reputation: 13794

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!");
}

Upvotes: 9

Related Questions