Reputation: 9
Just like the title said, i cannot use my object if i dipose it, i mean before i dispose it, i cannot use it. here is my code
Public Class Form1
Dim hasil(3) As Bitmap
Dim OneClickInsertGbr As New ArrayList
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
hasil(0) = New Bitmap("C:\Users\Robokidz\Google Drive\Tugas Akhir\Data Training\Foto Uang\1K\scan0001.jpg") 'This is my image
hasil(1) = New Bitmap("C:\Users\Robokidz\Google Drive\Tugas Akhir\Data Training\Foto Uang\1K\scan0001.jpg") 'This is my image
hasil(2) = New Bitmap("C:\Users\Robokidz\Google Drive\Tugas Akhir\Data Training\Foto Uang\1K\scan0002.jpg") 'This is my image
PictureBox1.Image = hasil(0)
hasil(0).Dispose()
hasil(1).Dispose()
hasil(2).Dispose()
End Sub
End Class
after i run, it generate error
Parameter is not valid.
after that check and see what is the reason behind the error, i know the problem is dispose. Because after i delete all of that dispose, it work fine, but the other problem rise.
Out of memory
i know this error, because i use too many memory.
my question is.
How to use an object and dispose it without getting that error?
Upvotes: 0
Views: 39
Reputation: 54417
The idea is that you dispose an object when you are finished using it. If you want the user to see an Image
displayed in a PictureBox
then you obviously haven't finished with that Image
, so you shouldn't be disposing it. If you are later going to replace that Image
in the PictureBox
with another one, THEN you should dispose the Image
that you are no longer going to display because you are now finished with it.
Here's an example of the sort of thing you need to do:
Private Sub SetPictureBox1Image(filePath As String)
If PictureBox1.Image IsNot Nothing Then
'Dispose an existing Image first.
PictureBox1.Image.Dispose()
End If
'Display the new Image.
PictureBox1.Image = Image.FromFile(filePath)
End Sub
Upvotes: 2