Opening a New Form Instance
Let’s kick this thing into gear by adding a second form class, Form2, to the project. To do this, select
Add Windows Form from the Project menu, make sure Windows Form is selected in the Templates pane of the Add
New Item dialog, keep the default name for the class module, and click Open.
We’re going to add a button to Form2 that will be used to display an instance of Form1.
Going back to Form1, it’s easy to add the code to the second button’s click event that will be used to hide
Form1 and show a new instance of Form2. Here’s what this click event procedure looks like:
private void btnForm2_Click(object sender, System.EventArgs e) {
this.Hide();
Form2 form2 = new Form2();
form2.Show();
}
The first line of this method used the this keyword to refer to the current instance of the Form1 class.
The Hide method is used to “cloak” the class instance so it is not visible on the screen (without deleting
the information it references). Next, a new instance of the Form2 class, using the variable named form2, is
declared and instantiated:
Form2 form2 = new Form2();
The Show method is used on the form2 variable to display the instance of the Form2 class:
form2.Show();
As far as it goes, this obviously works just fine, and does hide the first form and display an instance of
the second form.
However, all our difficulties are not over! This does not help you much if you want to recall a specific
form instance. It is probably the case in real world applications that you will be need as often to show
forms containing information already collected—entered by the user or obtained programmatically—as new form
instances. So, how is a specific form instance displayed? To find the answer to this question, tune into the
second part of this article.
|