How to change Connectionstring Name in Web.Config File at Runtime

Step 1: Add Connectionstring in your web.config file

  <connectionStrings>

    <add name="testing" connectionString="Pankaj123" />

  </connectionStrings>

Step 2: Add a textbox and a button on default.aspx page.
 

<div>

<asp:TextBox ID="txt_appkey" runat="server" Width="200px"></asp:TextBox>&nbsp;&nbsp;&nbsp;&nbsp;

<asp:Button ID="btn_submit"

runat="server" Text="Submit" onclick="btn_submit_Click" />

</div>

Step 3: Add namespaces on default.cs page as below.

using System.Configuration;

using System.Web.Configuration;

Step 4: Add the given code on your button_click event

 

Configuration connectionConfiguration = WebConfigurationManager.OpenWebConfiguration("~");

connectionConfiguration.ConnectionStrings.ConnectionStrings["testing"].Name = txt_appkey.Text;

connectionConfiguration.Save(ConfigurationSaveMode.Modified);

ConfigurationManager.RefreshSection("connectionStrings");

Step 5: Run application and enter a new name in textbox and click on button then check in your web.config file.(I have entered ABC in textbox), the connectionstring will look like below.

<connectionStrings>

 <add name="ABC" connectionString="Pankaj123" />

</connectionStrings>

Ebook Download
View all
Learn
View all