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

By Pankaj Pandey Jul 18, 2013
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" />


Pankaj Pandey
Pankaj Pandey

Hello Friend,This is Pankaj Pandey, Software Developer on .net Platform.I have knowledge of  Development in C#, as well as Sql server,and worked on Dot net 1.1,2.0,3.5,4.0 and sql server 2005,2008.Also worked... Read more