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

一曲冷凌霜 提交于 2019-11-29 01:14:25

The quick and dirty fix:

hfSupEmail.Value = dt.Rows(0)("SupEmail").ToString()

This works very well when your eventual target and the source data are already strings. This is because any extra .ToString() call for something that's already a string will generally be optimized by the jitter into a no-op, and if it's NULL then the resulting DBNull.Value.ToString() expression produces the empty string you want.

However, if you're working non-string types, you may end up doing extra work, especially with something like a DateTime if you want specific formatting.

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

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.

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.

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)()

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"), "")
FrankB

The easiest way is probably to just concatenate it with an empty string:

hfSupEmail.Value = dt.Rows(0)("SupEmail") & ""
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!