2011-05-10 139 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

相关问题