Jump to content
Xtreme .Net Talk

Recommended Posts

Posted

This is a section of one my my classes which populates itself using a datareader

 

If rdr.HasRows Then
           rdr.Read() ' get 1st row only
           Me.vehicleref = CInt(rdr(1))
           Me.make = rdr(2).ToString
           Me.model = rdr(3).ToString
           Me.IsLimited = CBool(rdr(4))
       
etc

 

Using the above code I ran into problems if the column in the database was null. The null value couldn't be cast to integer or boolean.

 

So, i changed the code to this. My question is if theres a better, more efficient approach than passing all those object variables around.

 

If rdr.HasRows Then
           rdr.Read() ' get 1st row only
           Me.vehicleref = CIntOrDBNull(rdr(1))
           Me.make = rdr(2).ToString
           Me.model = rdr(3).ToString
           Me.IsLimited = CBoolOrDBNull(rdr(4))
       
Private Function CBoolOrDBNULL(ByVal item As Object) As Boolean
       If Not item Is DBNull.Value Then
           Return CBool(item)
       Else
           Return Nothing
       End If
   End Function

   Private Function CIntOrDBNULL(ByVal item As Object) As Integer
       If Not item Is DBNull.Value Then
           Return CInt(item)
       Else
           Return Nothing
       End If
   End Function

 

Thanks

Posted

Don't allow nulls

 

I strongly suggest you use Option Strict in your code - you should not be returning Nothing from functions with Boolean or Integer return types.

 

The most correct fix for this would be to not allow null values in your data - if, as you previously mentioned, VehicleRef is your primary key then it should certainly not be null! Similarly, IsLimited should probably default to false rather than allowing nulls, since your code will end up treating null as false. It seems unlikely that a vehicle make or model name should ever be null either.

 

:)

Never trouble another for what you can do for yourself.
  • *Experts*
Posted

I've done exactly what you have Mondeo - differently named functions and a little more robust, but essentially the same concept.

 

I was hoping it would have been alleviated with .net 2.0 and the inclusion of nullable types. They help, but you still need to translate between DBNull and null/Nothing.

 

-ner

"I want to stand as close to the edge as I can without going over. Out on the edge you see all the kinds of things you can't see from the center." - Kurt Vonnegut

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...