Click here to Skip to main content
15,879,613 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I am Getting This Error Object cannot be cast from DBNull to other types. while opening connection in

What I have tried:

I have tried changing net driver From MYSQL Connector NET 8.0 to MYSQL Connector NET 8.2.0 but did not worked out. Earlier i was working fine, and Now it returing error
Richard MacCutchan 23-Dec-23 7:50am    
That suggest thatg you are trying to convert a DBNull element to an integer or something similar. So examine your code to see where it is failing.

1 solution

DBNull is a special type: it represents an "empty value" in database nullable column. When you issue a SELECT request against the database any matching rows that contain an SQL NULL value is returned as an instance of the DBNull Class[^]

Although it represents a NULL value in the DB, it isn't the same as a null value in your coding language - you can't directly cast it to any other type.
I'd suggest writing a generic conversion method similar to this:
public static T ConvertDBValue<T>(object o)
    if (o == null || o == DBNull.Value)
        return default(T);
        return (T)o;
And call that for each DB value you process.
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900