Wednesday, 28 February 2007

How to prevent Visual Studio 2005 designer from running your code

I created a control that inherited from System.Windows.Forms.TreeView. As it derived from the a control class Visual Studio 2005 (VS05) kindly automatically added to the Project Components section of the Toolbox (sidebar). From here I could happily drag'n'drop my control on to a form, which I did! However, my derived control upon construction performed a recursive enumeration of all the folders on my C: drive to populate the tree view. This was fine when the program was executing but it appears that in the design view VS05 also runs the constructor. This meant the recurisve and I did I say fairly time consuming enumeation occured in the design view effectively grinding all my work to a halt.

Anyway, I figured there must be a way to turn this off so; most likely using an Attribute. However, I could find nothing. Following some googling I came across some code that could be used detect from where your code was being run or to be more accurate was it being be run from within VS05.

So, just in case you have the same problem here it is:


if (this.Site == null this.Site.DesignMode == false)
; // This will only executee code when not running in VS05, i.e. normal execution

No comments: