Monday, June 29, 2009

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

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

When we try to assign a null value to string we get the below 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

1 comment:

  1. Exception:

    ASP .NET Error Exception Conversion from string "07-18-2009" to type 'Date' is not valid

    Here is the solution..

    http://muruganad.com/ASP.NET/ASP-.NET-Error-Exception-Conversion-from-string-07182009-to-type-Date-is-not-valid.html




    Thanks!

    Murugan Andezuthu Dharmaratnam

    www.muruganad.com

    ReplyDelete