• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1572
  • Last Modified:

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();

Open in new window

0
rmmarsh
Asked:
rmmarsh
  • 2
1 Solution
 
matthewrhoadesCommented:
I would add another line for the conversion.

Sorry for the sloppy looking formatting.
ing selectStatement = "select sum(cast(NbrOfCopies as integer)) from tBooks";
            FbCommand cmd = new FbCommand(selectStatement, bookConn);
            if (bookConn.State == ConnectionState.Closed)
                bookConn.Open();
            int Count = cmd.ExecuteScalar();  //  <-- crashes here!
if isDBNull(Count) = False then
myCount = ToInt32.Convert(Count)
            lblTotalCount.Text = "Total In Inventory:    " + myCount.ToString();

Open in new window

0
 
matthewrhoadesCommented:
Rather...
ing selectStatement = "select sum(cast(NbrOfCopies as integer)) from tBooks";
            FbCommand cmd = new FbCommand(selectStatement, bookConn);
            if (bookConn.State == ConnectionState.Closed)
                bookConn.Open();
            int Count = cmd.ExecuteScalar();  //  <-- crashes here!
            If IsDBNull(Count) = False Then
                myCount = ToInt32.Convert(Count)
            End If
            lblTotalCount.Text = "Total In Inventory:    " + myCount.ToString();
            myInternalConnection.Close()

Open in new window

0
 
rmmarshAuthor Commented:
I found a better way:  

            int Count = cmd.ExecuteScalar() is DBNull ? 0 : Convert.ToInt32(cmd.ExecuteScalar());



But thank you for putting me on the right track...
0
 
Guy Hengel [angelIII / a3]Billing EngineerCommented:
mmarsh: your "better" method risks to run the command object 2 times!!!!

hence:


object result = cmd.ExecuteScalar();
int Count = (result == DBNull.Value ? 0 : Convert.ToInt32(result));

Open in new window

0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now