Dim stream As New MemoryStream()
connect()
Dim command As New SqlCommand("SELECT image FROM tblHouseholdMembers WHERE id= '" & lvmem.FocusedItem.Text & "'", cn)
Dim image As Byte() = DirectCast(command.ExecuteScalar(), Byte()) --> 'Error message of null image
stream.Write(image, 0, image.Length)
cn.Close()
Dim bitmap As New Bitmap(stream)
pbProfilePic.Image = bitmap
我想在错误播放之前设置一个消息框来识别它是否为null。
答案 0 :(得分:3)
使用TryCast而不是使用DirectCast方法,然后检查转换结果是否为空:
Dim image As Byte() = TryCast(command.ExecuteScalar(), Byte())
if image isnot nothing then
stream.Write(image, 0, image.Length)
cn.Close()
Dim bitmap As New Bitmap(stream)
pbProfilePic.Image = bitmap
else
'Error message here
end if
答案 1 :(得分:0)
直接测试从数据库返回的字段是否为空的方法是:
if ValueFromDb is System.DbNull.Value then
' whatever you want to do in that case
当我第一次学习VB时,让我感到困惑的是,DB读取的空值不等于Nothing。它不是Nothing,而是System.DbNull.Value。
这些天我的大多数项目,我写了一个我称之为" denull"这就像是:
public shared function denull(value as object, defalt as object)
if value is system.dbnull.value then
return defalt
else
return value
end function
然后我在此函数中包装我从db读取的每个值。这节省了大量代码。
for each row in mydataset.tables(0).rows
foo=denull(row("foo"),"")
bar=denull(row("bar"),0)
plugh=denull(row("plugh"),nothing)
... etc ...