Using visual inheritance in Visual Studio .NET is a boon to object oriented development, but there are some pitfalls to keep in mind. One common problem is illustrated with a template design pattern, in which the base form references an object it defines that is instantiated in a derived form.
For example, let’s say you have a base form called BaseForm and a derived form called DerivedForm. BaseForm defines a protected member for your application’s CachedData object.
protected CachedData _cd;
Protected _cd As CachedData
In DerivedForm, the object is instantiated from a more specialized class (i.e., a class derived from CachedData) in the constructor:
_cd = new CachedDataSpecialized();
_cd = New CachedDataSpecialized()
The BaseForm, per the template pattern, uses the CachedData’s ImportantString() method to set its title, and calls this in its Load event:
private void BaseForm_Load(object sender, System.EventArgs e)
Private Sub BaseForm_Load(sender As Object, e As System.EventArgs)
Me.Text = _cd.ImportantString()
End Sub
This all should be fine, but when you open the DerivedForm in Visual Studio’s form designer, you will see that it does not work. Note this works in runtime correctly, but viewing this in the form designer causes an error:
"An error occurred while loading the document. Fix the error, and then try loading the document again. The error message follows: Object reference not set to an instance of an object."
The problem is that the form designer in Visual Studio .NET must actually instantiate the form and load it, and since the CachedData object is not set if the application is not running, you see the error above. To solve this problem, add a check for the CachedData object’s existence:
private void BaseForm_Load(object sender, System.EventArgs e)
{
if (null
!= _cd)
{
this.Text = _cd.ImportantString();
}
}
Private Sub BaseForm_Load(sender As Object, e As System.EventArgs)
If Not _cd
Is Nothing Then
Me.Text
= _cd.ImportantString()
End If
End Sub
You can now view and visually modify the DerivedForm in the form designer.
Thank you! Thank you! I just finished reading this document, which was part of a link in the recent Buzz newsletter. I have printed it for others to read, especially those skeptical on the powers of Access and its capabilities.
Darren D.
All Our Microsoft Access Products