views:

218

answers:

3

When you load an UserControl in the WinForm designer, VisualStudio executes the InitializeComponent() method of the control, but not its constructor. This really makes a difference because it's quite common to have some code in the constructor which cannot run at design time.

Unfortunately, when you add an UserControl to another control, VisualStudio runs the InitializeComponent() method of the parent control, which calls the constructors of the child controls, and if you've got an exception in those constructors, you're stucked.

How do you deal with this problem?

A: 

The workaround I'm using is to put my runtime initialization code in an InitializeRuntime() method, which I recursively call from the toplevel constructor. This solves the problem, but I always have to remember to add the call to InitializeRuntime() for every single UserControl I add instead of just drag'n'dropping the component using the designer.

Brann
+2  A: 

wrap the runtime only parts with:

If Not me.DesignMode Then
  'Runtime only here
End If
Pondidum
Caveat: DesignMode does not work properly in child controls. http://www.dotnetjunkies.com/WebLog/mjordan/archive/2003/12/01/4117.aspx
Robert Venables
Also, when you start debugging your program, it seems the code inside the "!this.DesignMode" section executes in your program (as expected), but also in the designer!
Brann
A: 

Why not use the OnLoadEvent in this scenario?

pointernil