0

我正在尝试将列表框的内容保存到文本文件中。它可以工作,但是我得到的不是输入到列表框中的文本,而是:

System.Windows.Forms.ListBox+ObjectCollection

这是我用于表单本身的相关代码。

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

该类只是一个简单的类:

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

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

3 回答 3

1

您将不得不一一写下这些项目:

using (StreamWriter sw = new StreamWriter("C:\\windowsNotes.txt") {
    foreach (var item in listBox1.Items) {
        sw.WriteLine(item.ToString());
    }
}
于 2013-04-27T22:19:19.700 回答
1

你不能只是做

   sw.Write(listBox1.Items);

因为它在集合对象本身上调用 .ToString() 。

尝试类似:

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

或者循环遍历每个项目和 ToString 单个项目。

于 2013-04-27T22:21:41.963 回答
0

您正在将集合的 ToString 写入输出流,而不是集合的元素。遍历集合并单独输出每个集合会起作用,我确信有一种简洁的 Linq(或更明显)的方式来做到这一点。

于 2013-04-27T22:20:53.100 回答