0

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

2
  • 1
    Post the database table definition, the query string, and the Account class constructor signature Commented Jul 19, 2015 at 2:06
  • try converting instead of casting Commented Jul 19, 2015 at 2:23

1 Answer 1

2

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"]);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.