简体   繁体   中英

Handling DBNull exception in VB.net

I'm trying to handle DBNull exception while reading data from database. It's my code:

...
Dim SQLRDAs SqlDataReader
...
val1= GetStringFromDB(Trim(SQLRD("Name")))
val2= GetStringFromDB(Trim(SQLRD("Level")))
val2= GetStringFromDB(Trim(SQLRD("blahblah")))
...
Public Function GetStringFromDB(ByVal inputValue) As String
     Dim outputValue As String

     If IsDBNull(inputValue) Then
         outputValue = "null"
     Else
         outputValue = inputValue
     End If

     Return outputValue
End Function

But still I get Conversion from type 'DBNull' to type 'String' is not valid. error. What's wrong?

This looks to me than a simple transposition error. You check for Not IsDbNull(..) but act like the value would be dbnull!

Public Function GetStringFromDB(ByVal inputValue) As String
   Dim outputValue As String

   If Not IsDBNull(inputValue) Then
       outputValue = inputValue
   Else
       outputValue = "null"
   End If

   Return outputValue
End Function

This should do the trick!

You have mixed the condition.

Change

 If Not IsDBNull(inputValue) Then
     outputValue = "null"
 ' ....

To

 If IsDBNull(inputValue) Then
     outputValue = "null"
 ' ....

Edit : Trim is executed before your DBNull-check. So i assume that that's causing your exception. Change your code to:

GetStringFromDB(SQLRD("Name")).Trim

Looks to me as if you try to Trim a DBNull value.

Either do GetStringFromDB(SQLRD("Name")).Trim() or inside GetStringFromDB

Edit: I'd wrap such stuff into an Extension, makes it easier to use and doesn't clutter your code.

  <Runtime.CompilerServices.Extension()>
  Public Function ReadString(ByVal this As SqlDataReader, ByVal index As Integer) As String
    Return If(Convert.IsDBNull(this.Item(index)), String.Empty, DirectCast(this.Item(index), String))
   End Function

    <Runtime.CompilerServices.Extension()>
    Public Function ReadString(ByVal this As SqlDataReader, ByVal columnName As String) As String
        Return If(Convert.IsDBNull(this.Item(columnName)), String.Empty, DirectCast(this.Item(columnName), String))
    End Function

IsDBNull checks if a value is missing. It is not equivalent to Nothing or to String.Empty. Are you sure that your inputValue contains DBNull.Value?

I will change your code in this way:

 If String.IsNullOrEmpty(inputValue) OrElse IsDBNull(inputValue) Then 
     outputValue = "null" 

Also note that you don't specify the type of inputValue, in my answer I assume As String

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM