Checking Null values

josh2009

Member
Joined
Sep 16, 2009
Messages
14
Programming Experience
Beginner
newbie here. Trying to check for nulls using the ff-

if currentCathRecord("Account_Number") Is Nothing Then
MessageBox.Show("Please enter Account Number or else ...")
return
End If

Nothing happens. No errors but message is not displayed. Field is defined as varchar(25) is SQL. Any help will be greatly appreciated. Thanks.
 
If this is coming from a DB then you use DBNull.Value when checking for null's:
VB.NET:
Expand Collapse Copy
If currentCathRecord("Account_Number") Is DBNull.Value Then
    MessageBox.Show("Please enter Account Number or else ...")
Else
    'Rest of program
End If
 
Thanks again for the help. It worked great for me. One other question, if I want to check for the opposite, field is populated, how do I use the dbnull.value? I tried -
VB.NET:
Expand Collapse Copy
if currentCathRecord("Account_Number") Is Not DBNull.Value Then
		MessageBox.Show("Account Number populated.")
		bFlag=False
		return
	End If
I got an error message. Thanks.
 
Thanks again for the help. It worked great for me. One other question, if I want to check for the opposite, field is populated, how do I use the dbnull.value? I tried -
VB.NET:
Expand Collapse Copy
if currentCathRecord("Account_Number") Is Not DBNull.Value Then
		MessageBox.Show("Account Number populated.")
		bFlag=False
		return
	End If
I got an error message. Thanks.
VB.NET:
Expand Collapse Copy
If currentCathRecord("Account_Number") IsNot DBNull.Value Then
    MessageBox.Show("Account Number populated.")
    bFlag=False
    return
End If
or
VB.NET:
Expand Collapse Copy
If Not (currentCathRecord("Account_Number") Is DBNull.Value) Then
    MessageBox.Show("Account Number populated.")
    bFlag=False
    return
End If
 
I have a couple of short functions that test for DBNull and was wondering if this is a good approach or not? Typically I'll read data and store it in a variable of a particular type...integer, string, decimal, etc. So I wrote a couple of short functions to make the overall code read better. Here's an example:

VB.NET:
Expand Collapse Copy
    Private Function ToBool(ByVal thing As Object, _
                         Optional ByVal rValue As Boolean = False) As Boolean
        If thing IsNot DBNull.Value Then
            Return CBool(thing)
        Else
            Return rValue
        End If
    End Function

Then I call it like this:

VB.NET:
Expand Collapse Copy
                    .IncludeNote = ToBool(dr("IncludeNote"))
                    .LiveItem = ToBool(dr("LiveItem"))
                    .Priceless = ToBool(dr("Priceless"))
                    .Active = ToBool(dr("Active"), True)

Makes sense? Is this a good way to deal with nulls?
 
Back
Top