HOW can i stop the form2 object from getting Disposed

mmb

Active member
Joined
Aug 1, 2004
Messages
42
Programming Experience
1-3
I have made a MDI I environment in VB.net.
Form1 is container and Form2 is MDIChild.
I have made a class to reference Form2 and a constructor, the code is

public class1
public f1 as new form1
public f2 as new form2

sub new()
f2.mdiparent = f1. activeform
end sub
end class

I have made a moodule also in which i have made the object of class1

module1
public cl as new class1
end

Now when i open form2 from the file menu of form1 it gets open.
Then when i close the form2 from the right hand corner cross botton and
the next time i open it from file menu the error come ..cannot open the
Disposed FORM2.

Pls tell me HOW can i stop the form2 object from getting Disposed
 

Paszt

Staff member
Joined
Jun 3, 2004
Messages
1,500
Location
Raleigh, NC - USA
Programming Experience
Beginner
Form2 gets disposed when closed. This is not something you would want to stop. Disposing has to do with releasing system resources. If not disposed, each time a new instance of Form2 is opened, more and more resources would be used.

When opening form2, what you want to do is check to see if it is Nothing or has been disposed; if it has, create a new instance and show that instance.

If Form1 is the main form of the App, I would suggest doing it like this:

VB.NET:
Friend Module Module1
    Friend f1 As Form1
    Friend f2 As Form2
End Module

'The code in Form1's load event handler:
'This allows reference to Form1 from Form2
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) _
  Handles MyBase.Load
    f1 = Me
End Sub

'the code for a MenuItem in a MainMenu control:
Private Sub miOpenForm2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
  Handles miOpenForm2.Click
    'notice the short-circuiting OrElse operator
    If f2 Is Nothing OrElse f2.IsDisposed Then
        f2 = New Form2()
    End If
    f2.MdiParent = Me
    f2.Show()
End Sub
See this article for a great explanation: Multiple Forms in VB.NET
 
Last edited:
Top Bottom