VB. How do you re-open Form2 that was called by Form1 after Form2 has been closed.

Cynolycus 260 Reputation points
2023-02-04T12:49:12.0566667+00:00

I have Form1 that has buttons on it, one of which opens Form2. Originally this button just used Form2.show but that resulted in a new form each time the button was clicked and I didn't want to have extra forms open for no reason so I changed the code.

Now I have:-

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        If subForm2 Is Nothing Then
            subForm2 = Form2
            subForm2.myCaller = Me
        End If
        subForm2.Show()
        subForm2.Focus() 'Bring the focus back to the Form if it is still open 
    End Sub

This works as needed except if Form2 is closed by clicking on the X in the top right corner then it can't be re-opened.

I would have thought that if Form2 was destroyed then the code in the If statement would be executed and a new instance of the form would be created, but instead the execution stops at subForm2.Show() because it can't show a destroyed form.

This would indicate that it bypassed the IF statement because subForm2 is NOT nothing even though it was destroyed.

I tried looking for a way to inform Form1 that Form2 was destroyed but I couldn't find it.

I don't want a child form or a dialouge form, just a seperate form that looks like a new program, In fact it is a new program as the main form is really just a control to open different programs in a package.

Is there a way to close a form and open it again?

Developer technologies | Windows Forms
Developer technologies | VB
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. LesHay 7,141 Reputation points
    2023-02-04T14:51:04.14+00:00

    Hi

    Here is one approach. You may or may not have data on the subform that you want preserved so here, the 'Visible' property is used to Hide/Show the Form.

    In calling Form (Here I use Form1)

      Dim subForm2 As New Form2
      rgs) Handles Button1.Click
        subForm2.mycaller = Me
        subForm2.Visible = Not subForm2.Visible
      End Sub
    

    In Form2 (subform)

    Option Strict On
    Option Explicit On
    Public Class Form2
      Public Property mycaller As Form
      Private Sub Form2_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
        Hide()
        e.Cancel = True
      End Sub
    End Class
    

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.