3
votes

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?

4
How would Visual Studio call InitialiseComponent without constructing an instance. The constructor is guaranteed to be called before InitialiseComponent is. - Ray Booysen
just try it : create a blank form, and add "throw new Exception()" at the very first line of the constructor (that is, before the call to Initializecomponent). You'll see that the winform designer can still load the form. - Brann

4 Answers

2
votes

wrap the runtime only parts with:

If Not me.DesignMode Then
  'Runtime only here
End If
1
votes

I found a solution in CodeProject that works for me:

if (System.ComponentModel.LicenseManager.UsageMode != 
    System.ComponentModel.LicenseUsageMode.Designtime)
{
    // Runtime only here
}
0
votes

Why not use the OnLoadEvent in this scenario?

0
votes

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.