When image field property in class is set with the image raw format of the same image from my database in picture box, it always throws this exception. In contrast, if the image in the picture box has been updated with one I select from my local PC directory, the update function work fine.
Below is my code:
Try
With mEmployee
If Miscellaneous.GetImageName(ofdPhoto).ToLower = "No_Photo.jpg".ToLower Then
.Image = Nothing
Else
Dim stream As New MemoryStream
pbImage.Image.Save(stream, pbImage.Image.RawFormat)
.Image = stream.GetBuffer()
End If
End With
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
Now everything has solved. This GDI+ generic error caused by the picture box itself. Actually, When I bound the record with image from the database and update that record without updating the image in the PictureBox, the image field has been set with old byte() data from the box, and that caused the error.
To solve this, I have declare a byte() type variable to store the temp image byte() data from the database, and when update, if the image has not been changed it will be set with the data from that variable. This is my code that solve everything:
Try
If Miscellaneous.GetImageName(ofdPhoto).ToLower = "No_Photo.jpg".ToLower Then
.Image = Nothing
Else
If isImageChanged = True Then
Dim stream As New MemoryStream
pbImage.Image.Save(stream, pbImage.Image.RawFormat)
.Image = stream.GetBuffer()
isImageChanged = False
ElseIf isRemoveImage = True Then
.Image = Nothing
isRemoveImage = False
Else
.Image = tempImage
End If
End If
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try