views:

242

answers:

3

I have a function that causes an exception in the designer. Can I avoid the call of the function if the designer loads it. Is there an attribute or something that is better than try catch?

Some more details: I mean the visual studio designer for win forms. My form is using a signleton wich calls LoadProject() on initialize. Now I want to avoid that the designer calls the LoadProject() function.

+2  A: 

Assuming this is WinForms - You can check if you are currently in DesignMode and just have your function return immediately.

There are some complexities that are fully explained in this article including a solution.

Eric J.
+1  A: 

You might try looking at this article on the MSDN about using the DesignMode property. This might help you out. You can wrap your code that throws an exception in this in a conditional that avoids the code at design time.

Please note this will not work in the constructor, because the designer has to instantiate the object and then sets the property.

Jason Jackson
+1  A: 

There are a few ways of detecting whether or not you are in design mode:

  • Check the value of the DesignMode property of the control. This does not work in a constructor of a control though, as it only returns true if the control has been sited, which does not happen until after the control has been created. It also has a bug whereby a custom control inside a custom control will always return false
  • Check whether the current application's path contains devenv.exe using Application.ExecutablePath.ToLower().IndexOf("devenv.exe"). If is does, the control is being instantiated by Visual Studio. A bit horrible, but it works.
  • Check LicenseManager.UsageMode for the value LicenseUsageMode.Designtime (have a look at my answer to Detecting design mode from a Control’s constructor for more details). Note that this does work in the constructor.

Wrapping the call to your function in any of these checks should solve your problem.

adrianbanks