VB.net making a form available throughout project

Murray Brown
Murray Brown used Ask the Experts™

In my VB.net project I declare my form in a public module as follows
Public F1 as New Form1

Then I open it using a button click

When I close the form and then try to open it again using F1.show I get an error saying that it cannot be accessed because it is disposed. How do I ger around this?

Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Mike TomlinsonHigh School Computer Science, Computer Applications, Digital Design, and Mathematics Teacher
Top Expert 2009
Here's one way:
Module Module1

    Private _F1 As Form1

    Public ReadOnly Property F1 As Form1
            If IsNothing(_F1) OrElse _F1.IsDisposed Then
                _F1 = New Form1
            End If
            Return _F1
        End Get
    End Property

End Module

Open in new window

Top Expert 2015
Idle_Mind method is the way to go if you really need to completely close the form when it is not needed.

In many situations, a simpler alternative would be to call it's Hide method instead of its Close method on the button that closes it.
You can see how I do it using MDI.

Public module declaration:

Friend Child2 As frmInventory

'I have a form named frmInventory, at my main menu, I access it when
'end-user clicks a button
'frmMDI is my Main Parent Form to hold all children forms

Private Sub btnInventory_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnInventory.Click
        If Child2 Is Nothing Then
            Child2 = New frmInventory()
            Child2.MdiParent = frmMDI
            Child2 = New frmInventory()
            Child2.MdiParent = frmMDI
        End If
    End Sub
Murray BrownASP.net/VBA/VSTO Developer


Thanks very much. Great answers

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial