'Conversion from type 'DBNull' to type 'String' is not valid
i am receiving this problem
Conversion from type 'DBNull' to type 'String' is not valid.
Line 501: hfSupEmail.Value = dt.Rows(0)("SupEmail")
i am very new to this, i am not really sure what is the exact problem could someone guide me?
Many thanks
Solution 1:[1]
Hope This Help....
dt.Rows(0)("SupEmail") returns null
To avoid this chcek before assigning
If Not IsDBNull(dt.Rows(0)("SupEmail")) Then
hfSupEmail.Value = dt.Rows(0)("SupEmail")
End If
Solution 2:[2]
Apparently your dt.Rows(0)("SupEmail") is coming as NULL from DB and you cannot assign NULL to string property. Try replacing that line with:
hfSupEmail.Value = If(IsDbNull(dt.Rows(0)("SupEmail")), String.Empty, dt.Rows(0)("SupEmail").ToString)
The code checks if value is NULL and if it is - replaces it with empty string, otherwise uses original value.
Solution 3:[3]
You should handle it at DB query level itself.
instead of "select name from student", use "select IsNull(name,'') as name from student"
In this way, DB will handle your NULL value.
Solution 4:[4]
To handle it from code, here is a small extension method
Imports Microsoft.VisualBasic
Imports System.Runtime.CompilerServices
Public Module HTMLExtensionMethods
<Extension()> _
Public Function DefaultIfDBNull(Of T)(ByVal obj As Object) As T
Return If(Convert.IsDBNull(obj), CType(Nothing, T), CType(obj, T))
End Function
End Module
Call it like this.
hfSupEmail.Value = dt.Rows(0)("SupEmail").DefaultIfDBNull(Of String)()
Solution 5:[5]
You can use the Field method of the Datarow combined with an If Operator to check for a Null value in one line like this. If it is null, you can replace it with an empty string (or another string of your choosing):
hfSupEmail.Value = If(dt.Rows(0).Field(Of String)("SupEmail"), "")
Solution 6:[6]
The easiest way is probably to just concatenate it with an empty string:
hfSupEmail.Value = dt.Rows(0)("SupEmail") & ""
Solution 7:[7]
con.Open()
cmd = New SqlCommand
cmd.CommandText = " select sum (Income_Amount) from Income where Income_Month= '" & ComboBox1.Text & "' and Income_year=" & txtyearpro.Text & ""
cmd.Connection = con
dr = cmd.ExecuteReader
If dr.Read = True Then
txtincome1.Text = dr(0).ToString ' ToString converts null values into string '
End If
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Rohit |
| Solution 2 | |
| Solution 3 | Amnesh Goel |
| Solution 4 | naveen |
| Solution 5 | Matt Wilko |
| Solution 6 | Joel Coehoorn |
| Solution 7 | naasir |
