2012-07-08 90 views
0

我有一個列表框,它讀取一個xml文件併爲用戶提供將項目從一個列表框添加到另一個列表框的功能。我想以某種方式保存所有項目名稱到一個XML文件,當用戶點擊一個特定的按鈕。但不是打印它打印的名稱"System.Windows.Forms.ListBox+ObjectCollection"如何將每個列表框項目保存到一個xml文件中

我以爲我可以做到這一點。

  XmlDocument doc = new XmlDocument(); 
      doc.Load("info.xml"); 
      XmlNode test = doc.CreateElement("Name"); 

      test.InnerText = listBox2.Items.ToString(); 


      doc.DocumentElement.AppendChild(test); 
      doc.Save("info.xml"); 

回答

3

這將返回的對象,而不是內容的類型。

listBox2.Items.ToString(); // System.Windows.Forms.ListBox+ObjectCollection 

如果你想每一個項目的全部內容保存在你的列表框,您應該通過每一個項目使用類似迭代:

foreach(var item in listBox2.Items) 
{ 
    // Do something with item 
    Console.WriteLine(item); 
} 

我建議使用一個StringBuilder來連接各個項目。

相關問題