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

Viewed 9136

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?

6 Answers

This is the only code that worked for me, using WPF UserControl on a Windows Form.

private bool? inDesignMode;
public bool IsDesignMode
{
  get
  {
    if (inDesignMode == null)
    {
      var prop = System.ComponentModel.DesignerProperties.IsInDesignModeProperty;

      inDesignMode = (bool)System.ComponentModel.DependencyPropertyDescriptor
          .FromProperty(prop, typeof(FrameworkElement))
          .Metadata.DefaultValue;

      if (!inDesignMode.GetValueOrDefault(false) && System.Diagnostics.Process.GetCurrentProcess().ProcessName.StartsWith("devenv", StringComparison.Ordinal))
        inDesignMode = true;
    }

    return inDesignMode.GetValueOrDefault(false);
  }
}
Related