Environment: I have a Visual Studio 2017 solution with a Model project containing Entity Framework (EF6) DbContext and POCOs, a data access layer project implementing the Repository and Unit Of Work patterns, and a WinForms UI project. In the UI main form there is a tab control and on one of the tab-pages there is a UserControl. On the UserControl there is DataGridView. In the UserControl's Load method, I get some data from the database via the UnitofWork (which gets data from EF) and use that data to populate the DataGridView (not using Data Binding).
Problem: At design-time, when I open the main form designer, I get a SQL Server connection Exception "A network-related or instance specific error occurred while establishing a connection to SQL Server. The server was not found or is not accessible....". The stack trace shows that it is running the code that populates the DataGridView, but cannot connect to the database at design-time. Everything works fine when I build and run the application.
Already researched/found: This SO answer shows that I can use if (!DesignMode) {...}
to wrap around code that I don't want to run at design time. That's okay but I'm going to be adding many more of these UserControls and I'm looking for a cleaner solution. Is there a simple (as in a few lines of code) way to...
or
I have not added any connection string to App.config. I'm simply working with Entity Framework's default connection to localDb.
After re-installing Windows, SQL Server and Visual Studio, I got the same behaviour. After more searching it has become obvious that Visual Studio will always run a UserControl's Load
method at design-time when you add the UserControl to a form or open the designer of a form that contains the UserControl. The solution is to test the value of the DesignMode
property in the Load
method.
private void MyUserControl_Load(object sender, EventArgs e)
{
if (!this.DesignMode)
{
// do stuff here, if it involves connecting to the database
}
}