Steven
Steven

Reputation: 310

Saving windows form listbox to a text file C#

I'm trying to save the contents of a listbox into a text file. and it works, but instead of the text entered into the list box, I get this:

System.Windows.Forms.ListBox+ObjectCollection

Here is the relevant code I'm using for the form itself.

listString noted = new listString();
        noted.newItem = textBox2.Text;
        listBox1.Items.Add(textBox2.Text);

        var radioOne = radioButton1.Checked;

        var radioTwo = radioButton2.Checked;

        var radioThree = radioButton3.Checked;

        if (radioButton1.Checked == true)
        {
            using (StreamWriter sw = new StreamWriter("C:\\windowsNotes.txt"))
            {
                sw.Write(listBox1.Items);
            }
        }
        else if (radioButton2.Checked == true)
        {
            using (StreamWriter sw = new StreamWriter("C:\\Users\\windowsNotes.txt"))
            {
                sw.Write(listBox1.Items);
            }
        }
        else if (radioButton3.Checked == true)
        {
            using (StreamWriter sw = new StreamWriter("../../../../windowsNotes.txt"))
            {
                sw.Write(listBox1.Items);
            }
        }
        else
        {
            MessageBox.Show("Please select a file path.");
        }
    }

The class is just a simple one:

 namespace Decisions
 {
     public class listString
     {
         public string newItem {get; set;}

         public override string ToString()
         {
             return string.Format("{0}", this.newItem);
         }
     }
 }

Upvotes: 0

Views: 5161

Answers (3)

Dave Hogan
Dave Hogan

Reputation: 3221

You cannot just do

   sw.Write(listBox1.Items);

as it's calling .ToString() on the collection object itself.

Try something like:

   sw.Write(String.Join(Environment.NewLine, listBox1.Items));

Or loop through each item and ToString the individual item.

Upvotes: 1

GreenCoder
GreenCoder

Reputation: 56

You're writing the ToString of the collection to the output stream rather than of the elements of the collection. Iterating over the collection and outputting each one individually would work, and I'm sure there there's a succint Linq (or even more obvious) way of doing that.

Upvotes: 0

Hans Passant
Hans Passant

Reputation: 942358

You will have to write the items one by one:

using (StreamWriter sw = new StreamWriter("C:\\windowsNotes.txt") {
    foreach (var item in listBox1.Items) {
        sw.WriteLine(item.ToString());
    }
}

Upvotes: 1

Related Questions