Form.Close

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I am trying to close a form from a button on another form. and it is not
working i am using code like:
dim frm1 as form1
frm1.close.

But it doesnt seem to work, please help
 
You're creating a new instance of "form1" and then "closing" it. You need to
get a reference to the running instance of "form1". Keep in mind, however,
that if "form1" is the startup Form then closing it will terminate the
application.
 
You don't create one, you track the one that you have. In VB.Net this
amounts to the word "Me". If you change the "Sub New" of the second Form to
accept a Form as a parameter as shown below...

Public Sub New(ByVal frmToClose As Form)
MyBase.New()
Me.formInstance = frmToClose
'This call is required by the Windows Form Designer.
InitializeComponent()
End Sub

.... add a new private field to store the reference to the Form...

Private formInstance As Form = Nothing

.... then inside the Click handler for the Button to close the other Form...

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
If (Not Me.formInstance Is Nothing) Then
Me.formInstance.Close()
Me.formInstance = Nothing
End If
End Sub

.... and finally, when this Form is created (let's call it Form2) you will
pass an instance of the appropriate Form to close. So, for example, if the
Form to close is the Form that creates and shows the Form2 instance, then
you could do something like this...

Dim frm As New Form2(Me)
frm.Show()

But keep in mind, if the Form to close is the startup Form then the
application will exit.
 
Back
Top