Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Dealing with DBNull results in a Datareader

Status
Not open for further replies.

oddball

Technical User
Mar 17, 2000
64
GB
Always have this problem whenever a DB query returns Null values for certain columns to my Datareader. I don't know how to check if any of the values returned are Null before setting the control Text property or SelectedIndex to it.

With the code below i get the following error message:

"Cast from type 'DBNull' to type 'String' is not valid"

===========================================================

Dim allocatedDA As Integer
Dim dr_id As SqlDataReader = users.GetSingleUserID(userId)

dr_id.Read()

allocatedDA.Text = CInt(dr_id("DA"))

dr_id.Close()

===========================================================

I have tried this:

===========================================================

If Not IsDBNull(dr_id("UserID")) Then

blahblah

End If

===========================================================

And this:

===========================================================

If Not (dr_id("UserID")) = Nothing Then

blahblah

End If

===========================================================

Aswell as this:

===========================================================

If Not (dr_id("UserID")) Is Nothing Then

blahblah

End If

===========================================================

But none of them seem to work! Help please.

cheers,

si
 
Try this:

Code:
If Not dr_id("UserID") is DBNull Then

    blahblah

End If

The cast warning '"Cast from type 'DBNull' to type 'String' is not valid"' gives a hint to the solution. You cannot convert a DBNull into a string. Therefore you should check the type of the object..
 
Tried it and i now get this error:

"'DBNull' is a type and cannot be used as an expression."

what else can i try,

cheers,

si
 
If Not isDBNull(dr_id("UserID")) Then
penny1.gif
penny1.gif
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top