如何处理vb.net中为null的Image

时间:2015-12-28 07:34:52

标签: vb.net sql-server-2008 datagridview

我有这个工作代码,当选择了datagridview时显示另一种形式的图像

display_errors(false); 
log_errors(true); 

问题是当我选择没有图像的记录时,我收到此错误:

Error 我希望用户选择记录,即使数据库中没有图像也没有错误。任何人都可以帮我解决这个问题。感谢

1 个答案:

答案 0 :(得分:1)

Decalre myPhoto()在Try ... Catch块之外。此外,您应该在错误和非错误情况下关闭连接(最后或使用Using关键字)。

Dim myPhoto() as Byte = Nothing
With cmd
    .Connection = cn
    .CommandText = "SELECT studImage FROM studentInformation WHERE Studentid = " & dgv1.SelectedRows(0).Cells(0).Value
End With

Try
  cn.Open()
  myPhoto = CType(cmd.ExecuteScalar(), Byte())
Catch ex as Exception

Finally
  If cn IsNot Nothing
     cn.Close()
  End If
End Try
return myPhoto

编辑:

Private Sub dgv1_DoubleClick(sender As Object, e As EventArgs) Handles dgv1.DoubleClick
    frmEdit.Show()
    Dim ms As MemoryStream
    Dim photo as Byte() = changephoto(CInt(dgv1.SelectedCells(0).Value))
    If photo IsNot Nothing
       ms = new MemoryStream(photo)
       frmEdit.PictureBox1.Image = Image.FromStream(ms)
    End If
End Sub