我收到了这个问题
从“DBNull”类型到“String”类型的转换无效。
第501行:hfSupEmail.Value = dt.Rows(0)( “SupEmail”)
我对此很新,我不确定究竟是什么问题 有人可以指导我吗?
非常感谢
答案 0 :(得分:24)
快速而肮脏的修复:
hfSupEmail.Value = dt.Rows(0)("SupEmail").ToString()
当您的最终目标和源数据已经是字符串时,这非常有效。这是因为对于已经是字符串的内容的任何额外.ToString()
调用通常会通过抖动优化为无操作,如果它为NULL,则生成的DBNull.Value.ToString()
表达式将生成您想要的空字符串。
但是,如果您正在使用非字符串类型,那么最终可能会执行额外的工作,尤其是在需要特定格式的情况下使用DateTime之类的工作。
答案 1 :(得分:5)
希望这个帮助......
dt.Rows(0)("SupEmail")
返回null
在分配之前避免这个chcek
If Not IsDBNull(dt.Rows(0)("SupEmail")) Then
hfSupEmail.Value = dt.Rows(0)("SupEmail")
End If
答案 2 :(得分:2)
显然,您的dt.Rows(0)("SupEmail")
在数据库中显示为NULL,并且您无法为字符串属性指定NULL。尝试用以下代码替换该行:
hfSupEmail.Value = If(IsDbNull(dt.Rows(0)("SupEmail")), String.Empty, dt.Rows(0)("SupEmail").ToString)
代码检查value是否为NULL,如果是 - 用空字符串替换它,否则使用原始值。
答案 3 :(得分:2)
您应该在数据库查询级别处理它。
instead of "select name from student", use "select IsNull(name,'') as name from student"
这样,DB将处理您的NULL值。
答案 4 :(得分:1)
要从代码处理它,这是一个小扩展方法
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)()
答案 5 :(得分:0)
您可以使用Field method of the Datarow结合If Operator来检查一行中的Null值。如果为null,则可以用空字符串(或您选择的其他字符串)替换它:
hfSupEmail.Value = If(dt.Rows(0).Field(Of String)("SupEmail"), "")
答案 6 :(得分:0)
最简单的方法可能是将它与空字符串连接起来:
hfSupEmail.Value = dt.Rows(0)("SupEmail") & ""
答案 7 :(得分:0)
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