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

前端 未结 5 1942
鱼传尺愫
鱼传尺愫 2020-12-15 19:54

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

5条回答
  •  -上瘾入骨i
    2020-12-15 20:40

    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.

提交回复
热议问题