11

I'm trying to add a column to an existing DataRow in C#. Afterwards the column will be filled with a single value from my database.

DataRow dr already exists and column "COLNAME" also exists.
comTBP is my SqlCommand.

dr["COLNAME"] = Convert.ToInt32(comTBP.ExecuteScalar());

This all works fine if there is a value in my database and ExecuteScalar() can get that value. If I test this code on my development server (local) it also works if ExecuteScalar() return null or DBNull and the value of my new column is 0. But the problem appears if I deploy my code to the production server. If I do everything the same, with the same database it throws an Exception with a message that it can't convert DBNull to Int32.
My question is why does this error appear on the production server and not on my local development server?

1
  • 1
    Most likely different data on production and development.
    – leppie
    Oct 28, 2011 at 9:35

3 Answers 3

19

ExecuteScalar returns DBNull for null value from query and null for no result. Maybe on your development server it never occured (null result from query).

10

Clearly in production you have either a NULL returned from the command execution or something different in the connectionstring or whatever; as a general rule you should always test for DBNull before casting/converting directly to another type the result of ExecuteScalar.

Check Rein's answer here (and vote him up) for his nice suggested solution:

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

9
  • 1
    Convert.ToInt32 from null results in 0. Oct 28, 2011 at 9:16
  • Then either he does not say all the truth or you are wrong ;-) I had similar issues in the past and solved by always checking for DBNULL before converting/casting Oct 28, 2011 at 9:18
  • 1
    I know it returns NULL in production.. it also returns NULL in development because it's the same DB. My question was why it returns NULL in development and DBNull in production? In development the casting from NULL to Int32 will result in 0 but in production it tries to cast from DBNull to Int32 and throws an exception
    – Yoni
    Oct 28, 2011 at 9:19
  • Well its written in documentaion : Return Value: A 32-bit signed integer equivalent to value, or zero if value is Nothing. Oct 28, 2011 at 9:19
  • AFAIK null in C# is NOT DbNull.Value !! Oct 28, 2011 at 9:21
2

Use the ISNULL() function in your SQL.

ISNULL ( check_expression , replacement_value )

ie...

SELECT ISNULL(SUM(Price),0) FROM Order

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.