Storing a Form Instance Variable As a Property
As I showed you, you can store a reference to a form (or any other class) instance in a static variable.
This works just fine but it is a bit quick and dirty because 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 is to store the form instance reference as a property of one of the classes.
Let’s add a property to the Form2 class that stores a reference to an instance of a Form class. (Note that I’m
creating the property using the more general Form class rather than the specific Form1, so a reference to an
instance of any class derived from the Form class can be stored in the property, not just a Form1 instance.)
You can use the C# Property Wizard, which is accessed from the Class View window, to jump start you in creating
the property, but it is easy enough to create it by hand in the Form2 class module.
Here’s the property added to the Form2 class module (it can go anywhere in the body of the class):
private Form m_InstanceRef = null;
public Form InstanceRef{
get {
 return m_InstanceRef;
}
set {
 m_InstanceRef = value;
}
}
Note the use of a private variable to store the value within the class instance, get and set accessors, and
the value keyword to set a new property value.
Next, the click event in Form1 that invokes Form2 needs to be modified to use the property rather than a public
variable, by assigning a reference to this (the current form instance) to the property:
private void btnForm2_Click(object sender, System.EventArgs e) {
this.Hide();
Form2 form2 = new Form2();
form2.InstanceRef = this;
form2.Show();
}
Finally, the property is used in Form2 to invoke the desired instance of Form1 (no qualifier is needed preceding
the property since it is a member of the current instance):
private void btnForm1_Click(object sender, System.EventArgs e) {
InstanceRef.Show();
}
As you can see, properties work very well for communicating form instances between the various modules in a
Windows form application, and provide a more encapsulated approach than using a public, static variable.
Although this two-part article has described the main pattern for Windows form interoperability in C#, obviously
as you get going you’ll find wrinkles that depend on the particular needs of your projects. For one thing, you may
have situations involving structures such as arrays or collections that point to multiple forms—and need to pick
the right reference from the various instances referenced in the structure. By showing you the general approach,
this article should help get you jump-started!
|