CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 15 of 24

Threaded View

  1. #22
    Join Date
    Aug 2006
    Posts
    145

    Re: Not actually a problem...

    Quote Originally Posted by WoF
    But to the last observation of hensa:
    I noticed this, too, last recently and was also a little perplexed. I would have expected the variables of a form to loose all their contents when the form got unloaded, but it seems not to be the case, indeed.

    It seems that a form, once loaded, is kept in a "cache" or something that it is present already when it has to be loaded again. It is as if it was only hidden, but gave a call to the Form_Unload() .
    This gave me a headache recently when I didn't know how a form's variable would remember a certain value after been unloaded and then been shown again. Is that behaviour documented, does anybody know?
    Mentioning this ties everything together very nicely.

    When you unload a named form (ie not instantiated with Set F = New Form1) a reference still exists to the object and as such the memory is not released. When you next load the object those variables that have not fallen out of scope will have their previous values preserved (ie. module-level variables).

    You can overcome this by setting the form reference to nothing: e.g
    Code:
    ' Inside Form1
    
    ' Assuming Form1 was loaded as:
    ' Load Form1
    'not
    'Set F = New Form1
    'Load F
    
    Private Sub Form_Unload(Cancel As Integer)
        Set Form1 = Nothing
    End Sub
    or you could also do this outside the form after unloading, or before you reload it.

    The reason you don't get any error when you next load the form (following the Set Form1 = Nothing) is the the form is essentially declared as Dim Form1 As New Form1 (if you get what I mean).

    Every time an object reference declared is used, VB checks to see if the object exists and if not, creates it. I saw comments above saying there's no difference in speed, but that's got to be the way it does it.
    Code:
    Dim col As New Collection
    
    Private Sub Command1_Click()
        Debug.Print ObjPtr(col)
        Debug.Print ObjPtr(col)
        Set col = Nothing
        Debug.Print ObjPtr(col)
    End Sub
    anyway, that's my two pennyworth, sorry if I've gone over anything already mentioned. That's the way I understand it - correct me if I'm wrong
    Last edited by bushmobile; August 9th, 2007 at 04:08 PM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured