The problem is that the when there are no records in your table the result of the
cmd.ExecuteScalar()
is
DbNull
. Which is a class. And you are trying to push it to an integer.
So my suggestion would be to first take the result of this into an implicitly typed variable(like var in C#, not sure about VB) and then check if its
DbNull
, push 0 to the Integer value else the actual value.
Alternate solution: Use the solution which Ashish suggested and put an ISNULL in your query itself.