Blog

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

Posted by Pankaj Pandey Blogs | ASP.NET Programming Jul 18, 2013
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>

COMMENT USING
PREMIUM SPONSORS
MCN is your source for developing solutions involving websites, mobile apps, cloud-computing, databases, BI, back-end services and processes and client-server applications.
SPONSORED BY
  • MCN is your source for developing solutions involving websites, mobile apps, cloud-computing, databases, BI, back-end services and processes and client-server applications.