Nov. 15, 2020, 11:16 a.m.
IT

Visual Studio Crashes When Designing Form

Ever had the problem where Visual Studio keeps on crashing when trying to open a Windows Form to design it? Well, I am building an Excel VSTO add-in that uses Windows Forms and an embedded User Control written in WPF to work around mixed HDPI and standard DPI monitor scaling issues. All went well until one day seemingly randomly Visual Studio refused to load the form. It had no issue loading the visual designer for the user control though.

Eventually I found this article, written 14 years ago. I am embarrassed that I did not think to do this myself. It turns our, I had combobox control in my user control that had a Grid_Loaded event attached. In the Grid_Loaded event handler I had code like this:

if (Globals.ThisAddIn.Credentials != null)
{
    textBoxURL.Text = Globals.ThisAddIn.Credentials.URL;
}

The IDE crashed on Globals.ThisAddIn being null - since it was not running in the Excel host process. The fix turned out to be trivial:

if (Globals.ThisAddIn?.Credentials != null)
{
    textBoxURL.Text = Globals.ThisAddIn.Credentials.URL;
}

What is happening here is that the Visual Studio designer instantiates the Windows Form and its embedded User Control when you open it in the designer, so the code is actually being executed and that caused the crash.

To be clear - this is still unacceptable behaviour from Visual Studio - it should never crash due to the contents of a source file.