2011-05-10 78 views
0

我正在使用.net 3.5 - 我嘗試列表框項目到文本文件時出現問題。我使用此代碼:如何保存文本文件中的列表框項目

if (lbselected.Items.Count != 0) { 
    string Path = Application.StartupPath + "\\ClientSelected_DCX.txt"; 
    StreamWriter writer = new StreamWriter(Path); 
    int selectedDCXCount = System.Convert.ToInt32(lbselected.Items.Count); 
    int i = 0; 

    while (i != selectedDCXCount) { 
    string selectedDCXText = (string)(lbselected.Items[i]); 
    writer.WriteLine(selectedDCXText); 
    i++; 
    } 

    writer.Close(); 
    writer.Dispose(); 
} 

MessageBox.Show("Selected list has been saved", "Success", MessageBoxButtons.OK); 

此訂單時出現的錯誤:

string selectedDCXText = (string)(lbselected.Items[i]); 

錯誤是:

無法轉換類型的對象的sampleData'爲類型「系統.String' 請幫我

回答

2

使用string selectedDCXText = lbselected.Items[i].ToString();

+0

雖然他可能想整個對象。 – 2011-05-10 04:53:17

+0

感謝它正在保存,但它正在將列表項目寫入文本文件其不保存項目名稱,但將此行保存在文本文件中Realtime_ALL.Form1 + SampleData Realtime_ALL.Form1 + SampleData – voipservicesolution 2011-05-10 04:55:59

0

您應該在類中覆蓋ToString方法,您要將哪些實例寫入文件。裏面ToString方法,你應該正確格式化輸出字符串:

class SampleData 
{ 
    public string Name 
    { 
     get;set; 
    } 
    public int Id 
    { 
     get;set; 
    } 

    public override string ToString() 
    { 
     return this.Name + this.Id; 
    } 
} 

然後用

string selectedDCXText = (string)(lbselected.Items[i].ToString()); 
+0

感謝它的工作,但除此之外,1是爲每個項目添加像這樣ALUMINIUM - 1個月1,鋁 - 2個月1,鋁 - 3個月1,ATF - 1個月1 1,ATF - 2個月1,BRCRUDEOIL - 1個月1,我該如何刪除1. – voipservicesolution 2011-05-10 05:17:38

0
Make sure that you have overridden the ToString method in your SampleData class like below: 

       public class SampleData 
{ 

           // This is just a sample property. you should replace it with your own properties. 
           public string Name { get; set; } 

           public override string ToString() 
           { 
            // concat all the properties you wish to return as the string representation of this object. 
            return Name; 
           } 

} 

Now instead of the following line, 
    string selectedDCXText = (string)(lbselected.Items[i]); 
you should use: 
    string selectedDCXText = lbselected.Items[i].ToString(); 

Unless you have ToString method overridden in your class, the ToString method will only output class qualified name E.G. "Sample.SampleData" 
+0

謝謝很多先生的工作 – voipservicesolution 2011-05-10 05:42:05

相關問題