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, 0, 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
它检查是否存在行以及该行是否包含数据。