Reputation: 199
I have this working code that displays an image in the other form when datagridview is selected
Private Sub dgv1_DoubleClick(sender As Object, e As EventArgs) Handles dgv1.DoubleClick
frmEdit.Show()
Dim ms As New MemoryStream(changephoto(CInt(dgv1.SelectedCells(0).Value)))
frmEdit.PictureBox1.Image = Image.FromStream(ms)
End Sub
Function changephoto(ByVal photo As Integer) As Byte()
cn.Open()
With cmd
.Connection = cn
.CommandText = "SELECT studImage FROM studentInformation WHERE Studentid = " & dgv1.SelectedRows(0).Cells(0).Value
End With
Dim myPhoto() As Byte = CType(cmd.ExecuteScalar(), Byte())
cn.Close()
Return myPhoto
End Function
The problem is when i select a record that has no image,I get this error:
I want the user to select records even if it is no image in the database without having error. Can anyone help me how to fix this. thanks
Upvotes: 0
Views: 1912
Reputation: 2167
Decalre myPhoto() outside of the Try...Catch block. Additionally you should close the connection in error and non-error case (Finally or alternatively with the Using keyword).
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
EDIT:
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
Upvotes: 1