Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to have code in the constructor that will NOT be executed at design time by Visual Studio?

I have a method call in the constructor of my user control that does something that won't work at design time (connecting to a database), and Visual Studio just bailed out when I tried to add that control to the GUI designer.
Sure, I can factor out that code to a separate method, but I don't like the idea that every time I use that object I need to remember to execute a certain method which is essential to that object's function (that's what the constructor is for!).

Is there something like a preprocessor symbol that I can mark my code with so that Visual Studio won't try to execute that code at design time?

like image 672
polyglot Avatar asked Nov 21 '09 06:11

polyglot


3 Answers

As others have stated, you can use the DesignMode property of the Component class. However, you will not be able to do this in the constructor of your control. The DesignMode property is always false in the constructor and methods called by the constructor. To get around this, re-factor your code to connect to the database in the OnLoad() callback. The DesignMode property is valid at that point. See here for the reasoning (look for the DesignMode section of the article).

I just ran across this blog entry that describes how to use the System.ComponentModel.LicenseManager.UsageMode property for doing the same thing. The blog describes an additional shortcoming of the DesignMode property when dealing with nested controls. Apparently, the UsageMode property doesn't have the same shortcomings and is available for use in the constructor. I cannot personally vouch for it, but might be worthwhile looking into.

like image 199
Matt Davis Avatar answered Nov 14 '22 13:11

Matt Davis


In Windows Forms?

if (!DesignMode)
{
    // code that shouldn't be executed at design time
}

As others have mentioned, this won't work in the constructor. It's often used in the Form.Load event.

like image 26
Michael Petrotta Avatar answered Nov 14 '22 13:11

Michael Petrotta


Have a look at this

Component.DesignMode Property

like image 44
Adriaan Stander Avatar answered Nov 14 '22 13:11

Adriaan Stander