DBNull check for ADODB.recordset

M

Mike OKC

VB 2005

All developers face this issue; so I'm sure Microsoft was a solution for it.

What is the built in method to check DBNull in a recordset field? NOT a
typed dataset.
I don't want to modify my sql script because it is created dynamically.
Below I have the old method to check for DBNull and to deal with DBNull in
the recordset. This method of coding is used over 80 times as I have over 80
fields to check for DBNull, so a one line method call off the value recordset
would be great.

If IsDBNull(rstSQLdetail.Fields("CaseNumber").Value) Then
txtCaseNumber.Text = ""
Else
txtCaseNumber.Text = rstSQLdetail.Fields("CaseNumber").Value
End If


It would be great to have something LIKE this,

txtCaseNumber.Text = rstSQLdetail.Fields("CaseNumber").Value.ChkDBNull("")

In this example the method would return a zero length string.
 
S

Stephany Young

Simply write yourself a function like:

Function ChkDBNull(ByVal value As Object) As String

If IsDbNull(value) Then Return String.Empty

Return value.ToString()

End Function

and then your 'check' becomes something like:

txtCaseNumber.Text = ChkDBNull(rstSQLdetail.Fields("CaseNumber").Value)

but .... DbNull.Value.ToString() returns an empty string, so, instead, you
can simply use:

txtCaseNumber.Text = rstSQLdetail.Fields("CaseNumber").Value.ToString()

The big gotcha of course is when you start dealing with column types that
don't represent a string per se, like datetime, bit, int, image, etc. You're
goning to have to figure out how to deal with the law of unintended
consequences.
 
L

Leon Mayne

Mike OKC said:
VB 2005

All developers face this issue; so I'm sure Microsoft was a solution for
it.

What is the built in method to check DBNull in a recordset field? NOT a
typed dataset.
I don't want to modify my sql script because it is created dynamically.
Below I have the old method to check for DBNull and to deal with DBNull in
the recordset. This method of coding is used over 80 times as I have over
80
fields to check for DBNull, so a one line method call off the value
recordset
would be great.

If IsDBNull(rstSQLdetail.Fields("CaseNumber").Value) Then
txtCaseNumber.Text = ""
Else
txtCaseNumber.Text =
rstSQLdetail.Fields("CaseNumber").Value
End If


It would be great to have something LIKE this,

txtCaseNumber.Text = rstSQLdetail.Fields("CaseNumber").Value.ChkDBNull("")

In this example the method would return a zero length string.

I just wrote an article about this:
http://leon.mvps.org/DotNet/CheckDbNull.html
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top