Closing a form from another form?

unbreakable

Newcomer
Joined
Oct 20, 2004
Messages
8
Hey guys,
I am opening Form2 when a button is clicked on Form1. After the user finishes entering some data in Form2, on clicking a button I want to close both Form2 and Form1. I could close Form2 that was very easy. But I could not close Form1. I tried using 'this.ParentForm.Close();' on the button click event on Form2. But that doesn't work. Any ideas on how to solve this?
-Unbreakable.
 
DiverDan said:
If Form1 is the startup form and you want to close everything then use End. If it's not then from Form 2 use Form1.Dispose.
How and where do I use 'end'?. Also I tried using Form1.Dispose from Form2 but there is no Dispose property for Form1. Please explain a little more in detail if possible.
 
Well the way i handle this is to create a public variable in form1:

Visual Basic:
'I usually put these after the Windows Form Designer generated code 
'region but before any control events or other functions
Public Shared objForm1 As Form

In Form1's load event set the value to form 1:

Visual Basic:
objForm1 = Me

In form2 import form 1:

Visual Basic:
Import YOURPROJECTNAME.Form1

Then when you want to close form1, and then close form 2 after, use:

Visual Basic:
objForm1.Dispose()
Me.close()
 
End is, however, not normally recommended as a good way of closing your application as it's good practice to clean up resources you are using explicitly. Closing the form your application is relying on for its message loop is generally a good idea instead.
 
I opened form2 as a showDialog window and now if I close form2, the control goes back to form1 and I just close it again there.
 
Look into Events

Define an Event in Form2, e.g. Event CloseMe; use RaiseEvent CloseMe in Form2 when you are ready for Form1 to take control.

In Form1, Dim withevents _Form2 as new Form2

In Form1, establish a procedure to respond to _Form2.CloseMe; in that procedure, you can _Form2.close and then Me.Close.

That way, you are no required to use .ShowDialog.

Events are very handy; I wish I had I discovered them earlier in my VB.Net career.





unbreakable said:
Hey guys,
I am opening Form2 when a button is clicked on Form1. After the user finishes entering some data in Form2, on clicking a button I want to close both Form2 and Form1. I could close Form2 that was very easy. But I could not close Form1. I tried using 'this.ParentForm.Close();' on the button click event on Form2. But that doesn't work. Any ideas on how to solve this?
-Unbreakable.
 
Back
Top