rmmarsh
asked on
How to test for DBNull when using ExecuteScalar?
I have the code below. It returns DBNull and crashes. How do I test for DBNull using ExecuteScalar?
string selectStatement = "select sum(cast(NbrOfCopies as integer)) from tBooks";
FbCommand cmd = new FbCommand(selectStatement, bookConn);
if (bookConn.State == ConnectionState.Closed)
bookConn.Open();
int Count = Convert.ToInt32(cmd.ExecuteScalar()); // <-- crashes here!
lblTotalCount.Text = "Total In Inventory: " + Count.ToString();
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
I found a better way:
int Count = cmd.ExecuteScalar() is DBNull ? 0 : Convert.ToInt32(cmd.Execut eScalar()) ;
But thank you for putting me on the right track...
int Count = cmd.ExecuteScalar() is DBNull ? 0 : Convert.ToInt32(cmd.Execut
But thank you for putting me on the right track...
mmarsh: your "better" method risks to run the command object 2 times!!!!
hence:
hence:
object result = cmd.ExecuteScalar();
int Count = (result == DBNull.Value ? 0 : Convert.ToInt32(result));
Sorry for the sloppy looking formatting.
Open in new window