2012-04-26 80 views
1

好吧我一直在这个工作了很多天,我知道我越来越接近完成它,但我不断收到错误。我得到的第一个错误是ArgumentException was unhandled这是这个:InvalidCastException在C#中未处理#

else 
{ 
    using (StreamWriter sw = File.AppendText(path))<--This is where is says 
    Argument exception was unhandled.    
    {  
     foreach (var item in employeeList.Items) 
      sw.WriteLine(item.ToString()); 
    } 

行,所以我用这个固定:

try 
{  
    StreamWriter sw = File.AppendText(path); 
    foreach (var item in employeeList.Items) 
     sw.WriteLine(item.ToString()); 
} 
catch 
{ 
    MessageBox.Show("Please enter something in"); 
} 

好了,现在我正在错误

无效的

强制转换异常无法强制转换 'WindowsFormsApplication2.Employee'类型的对象以键入'System.String'。

在此行中:

string path = txtFilePath.Text;  

if (File.Exists(path)) 
{ 
    using (StreamWriter sw = File.CreateText(path)) 
    { 
     foreach (string line in employeeList.Items)<-- Right here at the string line 
      sw.WriteLine(line); 
    } 
} 

我已经做了移动try和catch周围,我不断收到错误。我想要使​​用保存按钮的所有操作都是将所选记录写入txtFilePAth中指定的文件,而不截断当前内部的值。但我希望能够得到一个消息,如果你按下按钮时没有弹出某个盒子中的东西,并且我知道没有特定的路径是由于用户能够保存文件无论他们想要什么。有人能帮助我理解我做错了什么吗?

+0

你可能不应该试图通过只是用Try/Catch来解决你的问题。对于您执行foreach(EmployeeList.Items中的Employee e){...}'然后提取要写入文件的数据将更有意义。 – Thomas 2012-04-26 14:40:40

回答

4

employeeList.Items返回列表绑定到的数据项列表。这不是一个字符串列表,而是一个Employee对象列表(这似乎是您在应用程序中某处定义的类)。所以可以工作的语法是:

foreach (Employee employee in employeeList.Items) 
{ 
    // do something with the employee object 
} 
+0

谢谢你,我的大脑只是让这个项目感到困惑。 – shan 2012-04-26 14:51:59