Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ConfigurationManager connection string is null in UserControl

I have an application which gets data to the forms through a datalayer which uses something like this:

public DataTable get(String query, ArrayList parameters = null)
{            
   using (iDB2Connection cn =  new iDB2Connection(ConfigurationManager.ConnectionStrings["iseries"].ToString()))
   {
       // get the data and return them    
   }
}

I have forms which get data and this works fine.

However, I created a UserControl which gets data through this method which works fine when I run my project, however, the form which contains the UserControl throws a designer exception.

"To prevent possible data loss before loading the designer, the following errors must be resolved: "

I found that the error is located at the retrieval of the connection string from the <appSettings>.

It throws a nullpointerexception.

But only in design mode. When I ignore it, everything works fine, however, I would like to know how to resolve this.

Why are my <appSettings> null when accessing them through my UserControl?

UPDATE 1

It seems my UserControl doesn't recognize the <appSettings> at all.

When I put this code in my UserControl Load event I get a nullreference as well.

private void SelectUser_Load(object sender, EventArgs e)
{            
   txtLocation.Text = ConfigurationManager.AppSettings["location"].ToString();
}
like image 710
randomizer Avatar asked May 21 '14 14:05

randomizer


2 Answers

I found the solution, in designmode the usercontrol already executes the code in the Load-event. Because the App.config isn't available in designmode it isn't found and therefore not loaded. So I made a little check around it to check if in designmode or not:

bool designMode = (LicenseManager.UsageMode == LicenseUsageMode.Designtime);
if (designMode)
{
    string location = ConfigurationManager.AppSettings["location"].ToString();
}  
like image 183
randomizer Avatar answered Nov 08 '22 15:11

randomizer


The below article depicts this issue in WPF/Win Forms. Please have a look...

MS Forum

like image 24
Shubhojit Avatar answered Nov 08 '22 15:11

Shubhojit