如何解决无法将System.DBNull强制转换为System.Byte []
VB.NET和SQL Server。我正在尝试在系统上上传图片,但是出现错误提示
System.DBNull无法转换为System.Byte []。
这是我的代码
If id <> "" Then
Dim dt As DataTable = GetData((Convert.ToString("SELECT ImagePic FROM masterlist WHERE id ='") & Request.QueryString("id")) + "'") 'image data will be select depend on what user search in the serch textbox
If dt.Rows.IsNull.Count > 0 Then
Dim bytes As Byte() = DirectCast(dt.Rows(0).IsNull(0)("ImagePic"),Byte())
Dim base64String As String = Convert.ToBase64String(bytes,bytes.Length)
Image1.ImageUrl = Convert.ToString("data:images/png;base64,") & base64String
Else
Image1.ImageUrl = ""
Image1.AlternateText = "No image present in database with the name" 'if there is no image in db the messege will display
End If
End If
End Sub
我在这行出现错误
Dim bytes As Byte() = DirectCast(dt.Rows(0).IsNull(0)("ImagePic"),Byte())
有人知道如何解决这个问题吗?
解决方法
此:
Dim bytes As Byte() = DirectCast(dt.Rows(0).IsNull(0)("ImagePic"),Byte())
不是您被告知要做的。 IsNull
的要点是告诉您该字段是否为NULL,因此,是否有任何数据可读取。您首先检查它是否为NULL,然后仅在有要读取的数据时才读取数据。给定您已有的代码,明智的更改将是:
If dt.Rows.Count > 0 Then
对此:
If dt.Rows.Count > 0 AndAlso Not dt.Rows(0).IsNull(0) Then
这将检查是否存在一行并且该行包含数据。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。