Skip to main content
 首页 » 编程设计

c#之在 C# 中未处理 InvalidCastException

2024年02月23日21zengkefu

好吧,我已经为此工作了很多天,我知道我快要完成它了,但我总是出错。我遇到的第一个错误是 ArgumentException was unhandled,它是这样的:

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"); 
} 

好的,现在我得到了错误

of Invalid Cast Exception Unable to cast object of type 'WindowsFormsApplication2.Employee' to type '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 and catch around,但我不断收到错误。我想用保存按钮做的就是将选定的记录写入 txtFilePAth 中指定的文件,而不截断当前内部的值。但是我希望能够在你按下按钮时出现一条消息,但它弹出的那个框中没有任何东西。是的,我知道没有特定的路径是因为用户能够保存文件他们也想去哪里。有人可以帮助我理解我做错了什么吗。

请您参考如下方法:

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

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