简体   繁体   中英

WF C# VS2012 - InvalidCast Exception was unhandled by user code?

I was trying an example from a book on Windows Workflow and I got an error :

InvalidCast Exception was unhandled by user code

Unable to cast object of type 'System.DBNull' to type 'System.String'.

The exact code causing the error is :

 try
        {
            // Send data to workflow!
            IDictionary<string, object> outputArgs =
            WorkflowInvoker.Invoke(new CheckInventory(), wfArgs);

            // Print out the output message.
            Console.WriteLine(outputArgs["FormattedResponse"]);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }

The program will run, taking two questions from the user: color & make of a car and it then throws up this error. Any ideas ?

I guess the problem is the line

Console.WriteLine(outputArgs["FormattedResponse"]);

It seems like you're trying to convert outputArgs["FormattedResponse"] into a String (in order to write it to the console), but it evaluates to DBNull (ie, there is not such output message in the output args). Therefore, check whether outputArgs["FormattedResponse"] != DBNull.Value before printing it:

    var outputResponse = outputArgs["FormattedResponse"];
    if(outputResponse != DBNull.Value) 
        Console.WriteLine(outputResponse);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM