Ask the Expert

Problems closing Form1 in a two-form VB.NET project

I have a two-form VB.NET project and I am not using MDI for either form. I merely want to be able to go to Form2 from a click event on Form1. When this happens, I want Form1 to close! So my simple code would be:

dim Form2 as new Form2
Form2.Show()

    Requires Free Membership to View


Me.Close()

Doing this however shuts down BOTH forms. Any ideas?
Before I answer this, I just want to point out that in nearly all cases, applications that are switching forms on the user is not a good design. For one it's confusing to the user, and as you can tell, it really isn't something that's supported by the .NET Framework (or any framework for that matter). However, I do not know the particulars of your application so you may have a case where this makes perfect sense.

By calling Me.Close() on Form1, you are telling the application to end it's main thread, which ends the entire application. What you'll need to do is call Me.Hide() instead to hide the main form and let Form2 continue running as a modaless window. The problem is that when you close Form2, your application will continue to run because there's no automatic way to have the main form end when all modaless windows are closed. What you'll need to do is implement a way to pass an instance of Form1 to Form2. When Form2's Close method, which you'll need to override, is called, you can call Form1's close method.

This was first published in May 2004

There are Comments. Add yours.

 
TIP: Want to include a code block in your comment? Use <pre> or <code> tags around the desired text. Ex: <code>insert code</code>

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy
Sort by: OldestNewest

Forgot Password?

No problem! Submit your e-mail address below. We'll send you an email containing your password.

Your password has been sent to: