Conversion from type 'DBNull' to type 'String' is not valid

Suppose a field value of sql server table may be null.

If we try to assign that value to string we will get the error

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

Example


=======




Try
Dim strsql As String = "Select ErrDesc from DownloadDetails Where ID = 'D001'"
If conn.State = ConnectionState.Open Then conn.Close()
conn.Open()
Dim cmd As New SqlCommand(strsql, conn)
Dim result As String = cmd.ExecuteScalar()
{"Conversion from type 'DBNull' to type 'String' is not valid."}

catch ex as Exception
MsgBox (ex.Message)
End Try


To avoid this error

1. Should Check for dbNULL

If IsDBNull(cmd.ExecuteScalar) Then
result = ""
else
result = cmd.ExecuteScalar()
End If

2. Dim result As String = cmd.ExecuteScalar().ToString() 'Will convert the DBNull to String


Comments

Author: chrisy04 May 2010 Member Level: Bronze   Points : 1

If IsDBNull(cmd.ExecuteScalar) Then
result = ""
else
result = cmd.ExecuteScalar()
End If



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: