繁体   English   中英

从“DBNull”类型到“String”类型的转换无效

[英]Conversion from type 'DBNull' to type 'String' is not valid

我收到这个问题

从“DBNull”类型到“String”类型的转换无效。

第 501 行:hfSupEmail.Value = dt.Rows(0)("SupEmail")

我对此很陌生,我不太确定确切的问题是什么,有人可以指导我吗?

非常感谢

快速而肮脏的修复:

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

或对于 C#:

hfsupEmail.Value = dt.Rows[0]["SupEmail"].ToString();

当您的最终目标和源数据已经是字符串时,这非常有效,因为对已经是字符串的任何额外的.ToString()调用可能会被抖动优化为无操作,如果它是 NULL 结果DBNull.Value.ToString()表达式生成您想要的空字符串。

但是,如果您正在使用非字符串类型,您最终可能会做大量的额外工作,尤其是在您需要特定格式的DateTime或数值之类的东西上。 请记住,国际化问题意味着解析和组合日期和数字值实际上是非常昂贵的操作; 做“额外”的工作来避免这些操作通常是值得的。

希望这有助于.... dt.Rows(0)("SupEmail")返回 null

在分配之前避免此检查

If Not IsDBNull(dt.Rows(0)("SupEmail")) Then
    hfSupEmail.Value = dt.Rows(0)("SupEmail")
End If

显然,您的dt.Rows(0)("SupEmail")来自 DB 为 NULL,您不能将 NULL 分配给字符串属性。 尝试用以下内容替换该行:

hfSupEmail.Value = If(IsDbNull(dt.Rows(0)("SupEmail")), String.Empty, dt.Rows(0)("SupEmail").ToString)

代码检查值是否为 NULL,如果是 - 用空字符串替换它,否则使用原始值。

您应该在数据库查询级别本身处理它。

instead of "select name from student", use "select IsNull(name,'') as name from student"

这样,DB 将处理您的 NULL 值。

为了从代码中处理它,这里有一个小的扩展方法

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

这样称呼。

hfSupEmail.Value = dt.Rows(0)("SupEmail").DefaultIfDBNull(Of String)()

您可以使用DatarowField 方法结合If 运算符来检查一行中的 Null 值,如下所示。 如果它为空,您可以用空字符串(或您选择的另一个字符串)替换它:

hfSupEmail.Value = If(dt.Rows(0).Field(Of String)("SupEmail"), "")

最简单的方法可能是将它与一个空字符串连接起来:

hfSupEmail.Value = dt.Rows(0)("SupEmail") & ""
        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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM