How to change to connection string in web.config dynamically

In this blog, let's learn how to change a connection string in web.config file at runtime.
 
Step 1: Add this connection string in your web.config file in your ASP.NET web application or use an existing application. 
  1. <connectionStrings>  
  2. <add name="testing" connectionString="Pankaj123" />  
  3. </connectionStrings>  
Step 2: Add a TextBox and a Button control to Default.aspx page. 
  1. <div>  
  2. <asp:TextBox ID="txt_appkey" runat="server" Width="200px"></asp:TextBox>      
  3. <asp:Button ID="btn_submit"  
  4. runat="server" Text="Submit" onclick="btn_submit_Click" />  
  5. </div>  
Step 3: Add namespaces on default.cs page as below. 
  1. using System.Configuration;  
  2. using System.Web.Configuration;  
Step 4: Add the given code on your button_click event 
  1. Configuration connectionConfiguration = WebConfigurationManager.OpenWebConfiguration("~");  
  2. connectionConfiguration.ConnectionStrings.ConnectionStrings["testing"].Name = txt_appkey.Text;  
  3. connectionConfiguration.Save(ConfigurationSaveMode.Modified);  
  4. ConfigurationManager.RefreshSection("connectionStrings");  
Step 5: Run your application and enter a new connection string in the TextBox and click on the button. This will change the name in the web.config file. Using same approach you can also change the value of the connection string or any other config file key, value data.
  1. <connectionStrings>  
  2. <add name="ABC" connectionString="Pankaj123" />  
  3. </connectionStrings>