shan
shan

Reputation: 1371

InvalidCastException was unhandled in C#

Ok I have been working on this for many days and I know I am getting close to finishing it up but I keep getting errors. The first error I got was a ArgumentException was unhandledwhich was at this:

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

ok so I fixed it with this:

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

Ok now I am getting the error

of Invalid Cast Exception Unable to cast object of type 'WindowsFormsApplication2.Employee' to type 'System.String'.

On this line:

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

I have done moved the try and catch around and I keep getting errors. All I want to do with the save button is write the selected record to the file specified in the txtFilePAth without truncating the values currently inside. But I want to be able to have a message that comes across if you push the button without having something in that box it pops up.And yes I know there is not a specific path that is due to the user be able to save the file wherever they want too. Can someone please help me understand what I am doing wrong.

Upvotes: 1

Views: 2002

Answers (1)

David M
David M

Reputation: 72930

employeeList.Items returns you a list of the data items the list is bound to. This is not a list of strings, but a list of Employee objects (this seems to be a class you've defined somewhere in your application). So the syntax that would work is:

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

Upvotes: 4

Related Questions