views:

122

answers:

2

I am trying to compile a VB6 application, but it fails with the error, "Run-time error '91': Object variable or With block variable not set". It turns out the Resize event of a user control is firing during compilation and calling code that attempts to access an object that has not been instantiated yet.

Why is an event firing during compilation and is there any way to stop it?


Edit: I had some code here, but it's not relevant. The problem results from the fact that UserControl code (namely the Initialize, ReadProperties, Resize, and WriteProperties events) can execute at unexpected times. If the code in these events relies on other code to initialize any of its data structures, there's a good chance it's going to fail because that initialization code may not have executed. Especially during compilation when nothing is supposed to be executing! I'd call this a bug, but I'm sure Microsoft can rationalize it somehow.

+1  A: 

I think some events for user controls get executed during design time, at least for the purpose of rendering them in a consistent way.

recursive
In the case of user controls, this includes UserControl_Initialize()...which may trigger events.
Brian
They can do a lot more than that. See the EditAtDesignTime property of a UserControl.
Bob Riemersma
+4  A: 

Here's is a good article on the lifecyle of user control events

Understanding Control Lifetime and Key Events

Here is one snippet

Compiling the Project

When the project is compiled into an application or component, Visual Basic loads all the form files invisibly, one after another, in order to write the information they contain into the compiled file. A control instance gets the Initialize, ReadProperties, and WriteProperties events. The control's property settings are compiled into the finished executable.

It doesn't mention resize (which happens during run-time or when you physically resize the usercontrol on a container in design-time). Maybe your Initialize event is resizing the user control?

To avoid the error you can check if the offending object has been created before doing anything:

If Not Object Is Nothing then
  do something
DJ
Another snippet says, *Whenever a user runs the installed application or component, and the form is loaded, the control receives Initialize, ReadProperties, and Resize events.* If the forms are being loaded invisibly, that would explain why this event is firing.
raven