NDraskovic
NDraskovic

Reputation: 706

How to change connection string in app.config

I have a program that generates reports by using DataTables created by TableAdapters. Now my client has a new database, and he wants to be able to switch between the new one and the old one. I found that I can do it by changing the connection string in the app.config, but I don't know how to do it during run time. Can you suggest me a way? Thanks

Upvotes: 0

Views: 3584

Answers (2)

Vishal Suthar
Vishal Suthar

Reputation: 17183

You can define more than one connection strings like this:

<add name="Conn" connectionString="Data Source=PC\SQLEXPRESS;Initial Catalog=NHIB;Integrated Security=True" providerName="System.Data.SqlClient"/>-->
<add name="Conn1" connectionString="Data Source=WINSERVER;Initial Catalog=NHIB1;Integrated Security=True;" providerName="System.Data.SqlClient"/>

And after that you can use conn or conn1 based on your requirement..like:

SqlConnection con;
con = new SqlConnection(ConfigurationManager.AppSettings.Get("Conn"));  Or
con = new SqlConnection(ConfigurationManager.AppSettings.Get("Conn1"));

You can switch between them as below:

string connectionString = HttpContext.Current.Request.IsLocal ? 
ConfigurationManager.ConnectionStrings["Conn"].ConnectionString :
ConfigurationManager.ConnectionStrings["Conn1"].ConnectionString;
yourDataContext = new YourApplicationDataContext(connectionString);

Upvotes: 1

Oded
Oded

Reputation: 498884

I don't know how to do it during run time

Don't. You can have multiple connection strings in the app.config and access each when needed.

Configuration:

<connectionStrings>
  <add name="conn1" providerName="System.Data.SqlClient"
       connectionString="..." />
  <add name="conn2" providerName="System.Data.SqlClient"
       connectionString="..." />
</connectionStrings>

In code:

var conn1 = ConfigurationManager.ConnectionStrings["conn1"];
var conn2 = ConfigurationManager.ConnectionStrings["conn2"];

Upvotes: 7

Related Questions