2012-04-26 81 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