check bound datatable for null value vb.net

I am currently working in vb.net windows form applications with an sql back end. I have two datatables that are bound to two independent sql statements and both return two very simple datatables. I just need to check to see if there is a null value in either of the two tables, independently. The first query returns a single value, literally a single cell. I have always used the following code in a dgv to check for null

Dim Check As Integer = dt.Rows(1).cells(1).value

However this is not working here, it seems to be because the data type is an integer. Usually with a DGV I am doing a click event and am pulling from a dgv an end user can see.

The second sql query is just 2 cells. As in it has 2 rows and one column and I need to check both cells to make sure neither of them are null.

I have been looking around online but I cant find anything that seems to work for me.

------------------------update----------------------------

 Public Shared Function ToInt32(Value As Object) As Integer
    If DBNull.Value.Equals(Value) Then
        Return 0
    Else
        Return Convert.ToInt32(Value)
    End If
End Function



  Dim ncheck As Integer
  ncheck = SafeConvert.ToInt32(dt.Rows(1)(1))

How would i use this ncheck in a if statement to run an exit sub and a message box? It seems to me if ncheck is not an integer it is just going to crash on me.


Solution 1:

Here is a set of Safe Conversion methods you can use either as shared methods or maybe convert them to extensions:

Class SafeConvert   
    Public Shared Function ToInt32(Value As Object) As Integer
        If DBNull.Value.Equals(Value) Then
            Return 0
        Else
            Return Convert.ToInt32(Value)
        End If
    End Function

    Public Shared Function ToInt64(Value As Object) As Int64
        If DBNull.Value.Equals(Value) Then
            Return 0
        Else
            Return Convert.ToInt64(Value)
        End If
    End Function

    Public Shared Function ToDecimal(Value As Object) As Decimal
        If DBNull.Value.Equals(Value) Then
            Return 0
        Else
            Return Convert.ToDecimal(Value)
        End If
    End Function

    Public Shared Shadows Function ToString(Value As Object) As String
        If DBNull.Value.Equals(Value) Then
            Return String.Empty
        Else
            Return Convert.ToString(Value)
        End If
    End Function

End Class

Example:

Dim nCheck As Integer
nCheck = SafeConvert.ToInt32(dt.Rows(1)(1))
' or
nCheck = SafeConvert.ToInt32(dt.Rows(0).Item(1))

Of course, the row has to be valid and have a cell at that index, this is just testing for DBNull, not a NullReference.

Solution 2:

use DbNull.Value:

   If Not DbNull.Value.Equals(dt.Rows(1).Item(1).value) Then 
      ' do something
   Else 
      ' do something else 
   End If

or use

If dt.Rows(1).Item(1).value=DbNull.Value