VB.net making a form available throughout project

Murray Brown
Murray Brown used Ask the Experts™
on
Hi

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
F1.show

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?

Thanks
Comment
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
Commented:
Here's one way:
Module Module1

    Private _F1 As Form1

    Public ReadOnly Property F1 As Form1
        Get
            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
Commented:
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.Show()
        Else
            Child2 = New frmInventory()
            Child2.MdiParent = frmMDI
            Child2.Show()
        End If
    End Sub
Murray BrownASP.net/VBA/VSTO Developer

Author

Commented:
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