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

Step 1: Add Connectionstring in your web.config file


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


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


<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" />


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;



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.


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



Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now