Search code examples
wpfdesignernullreferenceexception

WPF Designer ONLY: NullReferenceException when loading connection string from app.config


Please help, for the sake of my non-pulled out hair...

The following code line:

this._connectionString = ConfigurationManager.ConnectionStrings["SqlConnectionString"].ConnectionString;

is causing me untold amounts of grief.

It is in a user control, currently in the control's Loaded event but I've also tried the constructor and just plain initializing the field to the value when it's declared. Whenever I do so, the WPF designer pitches a fit on any screen that uses said user control.

The code itself compiles fine, and runs with no issues. But it's turning into a real hampering in development not being able to use the designer at all. Does anyone have any clue what could cause this and a hint as to a good practice to avoid it in the future? I suspect it has something to do with trying to access the ConfigurationManager but I can't figure out where to put the line to make it stop.

Thanks.

PS: Visual Studio 2010 Premium


Solution

  • When you're working in design time, you should avoid loading this. Fill in the value with some other, appropriate default, instead:

    if (DesignerProperties.GetIsInDesignMode(this))
        this._connectionString = "Default";
    else
    {
        this._connectionString = ConfigurationManager
                                  .ConnectionStrings["SqlConnectionString"]
                                  .ConnectionString;
    }