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

后端 未结 8 732
攒了一身酷
攒了一身酷 2020-12-09 16:06

i am receiving this problem

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

Line 501: hfSupEmail.

相关标签:
8条回答
  • 2020-12-09 16:52

    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.

    0 讨论(0)
  • 2020-12-09 16:55

    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)()
    
    0 讨论(0)
提交回复
热议问题