Using a Static Variable to Refer to a Form Instance
Obviously, what we need is a variable that we can access that points to the specific instance of the Form1
class that we want to display. One way to do this is to use a public, static variable to hold the reference
to the instance. (The difference between static and instance class members, such as variables, is that static
members do not have to be instantiated.)
To do this, you can add a declaration just below the Form1 class declaration which declares a public, static
variable of type Form1 (I’ve named the variable staticVar):
public class Form1 : System.Windows.Forms.Form
{
public static Form1 staticVar = null;
...
}
By the way, there’s no reason you need to place this variable in the Form1 module—as long as it is public and
static, you can put it wherever you’d like. If you have multiple public, static variables, it may be a good idea
to create a class in a separate class module just for them.
Also note that I’ve initialized the variable using the null keyword so that it explicitly does not contain a
form reference.
Next, when it is time to display the Form2 instance, use the this keyword to store a reference to the current
Form1 instance in the staticVar variable:
staticVar = this;
Here’s the full revised code for the click event that displays the instance of Form2:
private void btnForm2_Click(object sender, System.EventArgs e) {
staticVar = this;
this.Hide();
Form2 form2 = new Form2();
form2.Show();
}
Now it’s easy to open the specific instance of Form1 that we want from Form2 just by using the reference
stored in the Form1.staticVar variable. Here’s the revised Form2 click event:
private void btnForm1_Click(object sender, System.EventArgs e) {
Form1.staticVar.Show();
}
Run the project again. Enter some text in the Form1 textbox, such as the phrase This time I’ll get back
to my instance! Click the button to hide it and show Form2. This time, when you click the Show Form1 button
on Form2, the specific instance of Form1 with your input will be displayed.
As it is, this works just fine. However, extensive use of public variables violates canons of good programming
practice (specifically, it is not encapsulated). In addition, it is probably excessively consumptive of resources.
A somewhat better solution I'll show you next is to store the form instance reference as a property of one of the classes.
|