Desposing of a bitmap. "OBJECT REFERENCE NOT SET TO AN INSTANCE OF THE OBJECT."

I am having memory problems.  I can watch the memory used climb to 100% during the operation of the program and then fall off again.  The sample code included contains the area where I suspect my problem lies.  I am declaring a new bitmap each time I run the procedure and not disposing of the old one.  As you can see, I have tried the simple direct approach to getting rid of the old bitmap by simply disposing of it.  Unfortunately, VB won't let me do that.  When it gets to that line of code, I get an exception:
"OBJECT REFERENCE NOT SET TO AN INSTANCE OF THE OBJECT."

I don't have a clue as to what that means or how to fix it.

Can someone please give me a clue

Thanks,
Dick

bmp2.Dispose()

Dim g1 As Graphics = Me.CreateGraphics()

bmp2 = New Bitmap(w, h, g1)

g1 = Graphics.FromImage(bmp2)

dc1 = g1.GetHdc

BitBlt(dc1, 0, 0, w, h, dc2, X, Y, 13369376)

g1.ReleaseHdc(dc1)



Answer this question

Desposing of a bitmap. "OBJECT REFERENCE NOT SET TO AN INSTANCE OF THE OBJECT."

  • Liet29

    THe simple way to get rid of an object, is to check if it's nothing...  It's just easier to check and dispose if needed then to assume every time you get there.


    Here's a quick example.



            Dim pb1 As New PictureBox
            Dim bmp1 As New Bitmap(pb1.Height, pb1.Width)
            pb1.Image = bmp1

            If Not (pb1.Image Is Nothing) Then
                pb1.Image.Dispose()
                pb1.Image = Nothing
            End If

            If Not (bmp1 Is Nothing) Then
                bmp1.Dispose()
                bmp1 = Nothing
            End If

     



    Dustin.


  • Samir S.

    It means that bmp2 doesn't point to an object (it's Nothing).

    There is a problem with your use of the Graphics class, though. You're creating two each time (Me.CreateGraphics and Graphics.FromImage), but you're not disposing of either one.

  • RavuriSurya

    Hi Daniel,

    But it isn't nothing.  I put the same instruction following the line where I called the code I posted from and it works.  So obviously it's something.  It really bugs me when a compiler will accept an instruction in one procedure but not another.  There is absoulutely no difference in scope from where the instruction works and where it doesn't.

    Thanks for the tip about nor disposing of both instances.  I will take a harder look at it.

    Thanks again,
    Dick

  • Desposing of a bitmap. "OBJECT REFERENCE NOT SET TO AN INSTANCE OF THE OBJECT."