2016-07-22 91 views
0

因此,我正在一个项目中使用图像,并且我必须从数据库检索图像到我的VB.Net应用程序,问题是在数据库中检索NULL时,它会返回一个字节不应该为空的错误,这里有一篇文章说明“字节不应该为空”,但是我直接将数据从我的存储过程转换到我的应用程序,就像这样。如何检查VB.net中的空图像

Sub searchEmpPic(ByVal employeenumber As String) 

     Dim sqlcomm As New SqlCommand 
     Dim dt As New DataTable 
     Dim dta As New SqlDataAdapter 

     With sqlcomm 

      conn.Open() 
      .Connection = conn 
      .CommandText = "dbo.getEmpPic" 
      .CommandType = CommandType.StoredProcedure 
      .Parameters.AddWithValue("@eNum", employeenumber) 
      'error happens during DirectCast 
      If DirectCast(.ExecuteScalar, Byte()) Is Nothing Then 
       loadDefaultPic() 
       conn.Close() 
      Else 
       Dim imagedata As Byte() = DirectCast(.ExecuteScalar, Byte()) 
       Dim ms As New MemoryStream 
       ms.Write(imagedata, 0, imagedata.Length) 
       Me.pbEpic.BackgroundImage = Image.FromStream(ms, True) 
       pbEpic.BackgroundImageLayout = ImageLayout.Zoom 
       conn.Close() 
      End If 



      .Dispose() 
     End With 




    End Sub 

我怎么解决这个问题?

这是存储过程中的数据键入要与数据库中的工作

ALTER procedure [dbo].[getEmpPic] 

@eNum as varchar(10) 

as 

begin 

    select isnull(employee_picture,0) from employee where employee_id = @eNum 

end 

回答

1

NULL值以完全相同的方式处理,不管。在查询数据库时,您将获得预期类型的​​值,或者如果数据库字段为NULL,则会得到DBNull.Value。你如何发现这取决于你在做什么,但在ExecuteScalar的情况下,你可以这样做:

'result will be type Object as that is what ExecuteScalar returns.' 
Dim result = myCommand.ExecuteScalar() 

If result Is DBNull.Value Then 
    'The database produced NULL so there is no value.' 
    '...' 
Else 
    Dim value = DirectCast(result, Byte()) 

    'Use value here.' 
End If 

另一个变体是:

Dim value = TryCast(myCommand.ExecuteScalar(), Byte()) 

If value Is Nothing Then 
    'The database did not produce a Byte() so the field was NULL.' 
    '...' 
Else 
    'Use value here.' 
End If 

在第二种情况下,value会推断为类型Byte(),但如果ExecuteScalar未返回该类型的对象,则将为Nothing

+0

我用你的第一个变体,我遇到了麻烦,因为有一个错误,指出参数无效线'Me.pbEpic.BackgroundImage = Image.FromStream(ms,True)'我删除了我的存储过程的isnull函数,现在效果很好! – UserSeriously

+0

我修复了它,对于迭代感到抱歉! – UserSeriously