Abraham Olatubosun

Abraham Olatubosun

  • NA
  • 471
  • 113k

How to Change web.config ConnectionString dynamically

Apr 4 2017 6:59 AM
Dear Code Master,
 
 I hope this question meet in good health, i am writing an application, i have finished writing and every thing is working we upload it to cloud for the client from time to time their is the need to make some amendment that also had to affect the database.
When we re-upload we need to make changes to the connection string in web.config, we them impliment changing the web.config dynammically that ir from run time we put some text boxes and a submit button when the button is click by the client it should edit the web.config connectionstring section and update it with the new connection string.
we have tried the following:
  1. // ===========================================  
  2.         // The content of pathname is shown below  
  3.         //  string pathname = "~/web.config";  
  4.         //============================================  
  5.   
  6.         System.Configuration.Configuration Config1 = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(pathname);  
  7.         ConnectionStringsSection conSetting = (ConnectionStringsSection)Config1.GetSection("connectionString");  
  8.         ConnectionStringSettings StringSettings = new ConnectionStringSettings("NIQSDB""Data Source=" + ServerName + ";Database=" + DBaseName + ";User ID=" + UserID + ";Password=" + PSSWD + ";");  
  9.         conSetting.ConnectionStrings.Remove(StringSettings);  
  10.         conSetting.ConnectionStrings.Add(StringSettings);  
  11.         Config1.Save(ConfigurationSaveMode.Modified);  
and i am getting the following error 

Object reference not set to an instance of an object.

 at 
conSetting.ConnectionStrings.Remove(StringSettings);
please what am i doing wrongly.

thank you

Answers (1)