guyz i need help, i encounter an error saying "Cannot access a disposed object. Object name: 'Form2'." I encountered it after I closed the child form named Form2 and then click again the button1 to show it again. Hope you help me guyz

here's my code

Public Class Form1
    Dim frm2 As New Form2
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        frm2.MdiParent = Me
        frm2.Show()
    End Sub
End Class

Hi,

Declare your form2 inside the Button event, like this:

Public Class Form1
        Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim frm2 As New Form2
        frm2.MdiParent = Me
        frm2.Show()
    End Sub
End Class

i tried what you said but when i click the button again a new form was created again and evrytime i clicked it a another form was being created. It shoul not happening.

Use this code:

There might be some synatx errors. Sorry for that. I don't have VB.NET installed.

Public Class Form1

Dim frm2 As New Form2

Function CheckForm(ByVal f as Form) As Boolean
     Dim openForm as Form
     Foreach openForm in Application.OpenForms
        if openForm == f Then return (true)
     End foreach
        return (false)
End Function

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        [B]if CheckForm(frm2) == False Then frm2 = new Form2()[/B]

        frm2.MdiParent = Me
        frm2.Show()
    End Sub
End Class

Here's what I usually do, following Luc001's example.
Add a handler for the FormClosed event.
When you close the newly opened form, the event will be triggered and dispose of the object.
And any future openings of the form will be with a fresh copy.

Public Class Form1
        Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
                Dim frm2 As New Form2
                frm2.MdiParent = Me
                frm2.Show()
                AddHandler frm.FormClosed, AddressOf frm_Closed
    End Sub

        Private Sub frm_Closed(ByVal sender As Object, ByVal e As EventArgs)
                DirectCast(sender, Form2).Dispose()
        End Sub
End Class

Hi,

After some testing found a way to show only one Form.
That means that like in your example you have a Form2.
Now try this code:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Form2.MdiParent = Me
        Form2.Show()
        Form2.Focus() ' you need to focus it, if it's behind another Form
    End Sub

You'll see that the Form2 will be shown only ones.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.