1

In this Winform app, I have some forms loading SQL methods. They execute that code as expected at runtime, every time they are loaded.

But why do they execute the load method every time I open them in Visual Studio?

I'm using Visual Studio 2015 CE

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459

1 Answers1

3

Because VS designer executes constructors of forms to display it in design time.
To prevent it, you can use this code to check DesignMode property:

if (!DesignMode)
{
    //... run sql
}

More complicated with LicenseManager:

if (LicenseManager.UsageMode != LicenseUsageMode.Designtime)
{
    //... run sql
}
Backs
  • 24,430
  • 5
  • 58
  • 85
  • Ho! Are you sure? I've always thought the designer is smarter and instantiates the base class of the form (typically Form) and then parses the code in InitializeComponent() specifically to avoid running actual form code in the designer. Is this something that has changed in recent versions of VS? See answers to this question of mine: http://stackoverflow.com/questions/872536 – Serge Wautier Oct 01 '16 at 15:14
  • Did not work for me. Still runs sql code when I open in design view – Antony Lopez Oct 01 '16 at 15:16
  • @AntonyLopez added one more case – Backs Oct 01 '16 at 15:18
  • Did not work for me eider. Still runs sql code when I open the Form in design view. I implemented it on all sql code. – Antony Lopez Oct 05 '16 at 18:43
  • The SQL code is in a UserControll that runs on a Form. And When I open that Form in design view, all hell breaks lose. Sorry for the late feedback. – Antony Lopez Oct 05 '16 at 18:49