2013-04-27 65 views
0

我试图将列表框的内容保存到文本文件中。它的工作原理,而不是文本输入到列表框中,我得到这个:将Windows窗体列表框保存为文本文件C#

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

循环'listBox1.Items'并写入它们 – I4V 2013-04-27 22:19:49

回答

1

你不能只是做

sw.Write(listBox1.Items); 

,因为它是集合对象本身调用的ToString()。

试着这么做:

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

或者遍历每个项目和toString的单个项目。

+1

+1'Newline' =>'NewLine' – I4V 2013-04-27 22:26:17

+0

Opps ...谢谢。我忘了添加 - 这是未经测试的代码,但原则应该工作 – DaveHogan 2013-04-27 22:28:14

+0

谢谢,帮助了一堆 – Articulous 2013-04-27 22:50:28

1

你将不得不写的项目一个接一个:

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

你写了集合的对的ToString输出流而不是集合的元素。迭代收集并单独输出每一个都是可行的,我确信那里有一个令人沮丧的Linq(或更明显的)方法。