简体   繁体   中英

C# System.InvalidCastException: Specified Cast is not valid

I've been struggling with one problem these past few hours.

I keep getting an error and it tells me that the specified cast is not valid. I'm able to change the values on the database using the stored procedure. However, when I try doing it with the executable I get that error.

This is the error

System.InvalidCastException: Specified cast is not valid.
at Administrator_Panel.DB.ReadAccountInfo(String UserID, In32& Count)

This is the code.

 public static Account ReadAccountInfo(string UserID, out int Count)

 if (Reader.Read())
                ReturnValue = new Account((int)Reader["UserUID"],
                                            (string)Reader["Pw"],
                                            (bool)Reader["Admin"],
                                            (bool)Reader["Staff"],
                                            (short)Reader["Status"],
                                            (int)Reader["Point"],
                                            (int)Reader["DaemonPoints"]);

Any help would be appreciated. :) Thank you

See this answer: How to (efficiently) convert (cast?) a SqlDataReader field to its corresponding c# type?

You can't just cast SqlDataReader fields to their corresponding value types because of the possibility of nulls. You can use nullable types but it's likely your Account object isn't setup to take nullable types.

One way you can try to handle this is to add null checking:

 ReturnValue = new Account(Reader["UserUID"] == DBNull.Value ? 0 : (int)Reader["UserUID"] ,
                           Reader["Pw"] == DBNull.Value ? "" : Reader["Pw"].ToString(),
                           Reader["Admin"] == DBNull.Value ? false : (bool)Reader["Admin"],
                           Reader["Staff"] == DBNull.Value ? false : (bool)Reader["Staff"],
                           Reader["Status"] == DBNull.Value ? (short) 0 : (short)Reader["Status"],
                           Reader["Point"] == DBNull.Value ? 0 :  (int)Reader["Point"],
                           Reader["DaemonPoints"] == DBNull.Value ? 0 : (int)Reader["DaemonPoints"]);

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