2

Need connect to the database and get some values inside the Load event of my user controller. But I'm getting a null reference error when every time I drag and drop my user control to a windows form. It seems like visual studio is unable to initialize the connection string in the design time(according to stack trace ) .Connection string has been defined inside the app.config file. So far I googled this error and tried adding following code block but couldn't work.

    if(System.ComponentModel.LicenseManager.UsageMode != System.ComponentModel.LicenseUsageMode.Designtime)
{
     _strcon = ConfigurationManager.ConnectionStrings["defaultConnection"].ConnectionString;
}

Connection String

<add name="defaultConnection"
providerName="System.Data.SqlClient" connectionString="Dbhostname;Initial Catalog=employee;User ID=sa;Password=password;Enlist=False;MultipleActiveResultSets=true;" />

There is no any compile time errors or run time errors. The error is windows form designer is not loading

enter image description here

Oshada Ekanayake
  • 360
  • 1
  • 2
  • 12
  • 1
    Possible duplicate of [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – SᴇM Aug 27 '18 at 11:46
  • 1
    @SeM I know about the NullRefferenceException. My solution is build without any errors and also not getting run-time errors. Only problem is windows form designer not loading – Oshada Ekanayake Aug 27 '18 at 12:00
  • 1
    @OshadaEkanayake You arre getting that error, because you're trying to access `ConfigurationManager.ConnectionStrings` in design time, which is `null` at that moment. – SᴇM Aug 27 '18 at 12:04
  • Try to search a bit on `design time properties`; you need to give the connectionstring a valid value, not using the configurationmanager directly. – Stefan Aug 27 '18 at 12:05
  • I added a message box to check whether the error is getting in designtime but message box returns runtime MessageBox.Show(LicenseManager.UsageMode.ToString()); – Oshada Ekanayake Aug 27 '18 at 12:37
  • @Stefan But I don't want to hard code the connection string therefore i have to use Configuration Manager – Oshada Ekanayake Aug 27 '18 at 12:47
  • 2
    You can check, whether the control is in design mode, see the `DesignMode` property of your user control. If it is not (runtime mode), initialize it from your configuration file as written above. Otherwise set it to an empty or another default string. – KBO Aug 27 '18 at 13:41

0 Answers0