简体   繁体   中英

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

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM