2013-04-27 71 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(或更明顯的)方法。