Vivek Parikh
Vivek Parikh

Reputation: 627

how to change connection string initial catalog

I have a connection string in web config file. I used this connection with name in all my files.

connection string is like

<add name="connectionname" connectionString="Data Source=DEVELOPER1;Initial Catalog=dbname;Persist Security Info=True;User ID=sa;Password=some"/>

I want to change initial catalog (database name) in my login page as per dropdown and that change will remain same for the application.

Upvotes: 11

Views: 20765

Answers (2)

freedeveloper
freedeveloper

Reputation: 4082

To change the connection string without modify it, you should do the following procedure:

  1. Create a SqlConnectionStringBuilder object Assign your original connection string to it
  2. Change the parameters that you want in the created SqlConnectionStringBuilder object.
  3. Adding the SqlConnectionStringBuilder ConnectionString property to your DbConnection Object.

See the following example: (suppose that first you are created a normal DbConnection with your original conexion string (name db here)):

if (db != null)
{
    SqlConnectionStringBuilder conn = new SqlConnectionStringBuilder(db.ConnectionString)
   { ConnectTimeout = 5, InitialCatalog = "your CatalogName" }; // you can add other parameters.
      db.ConnectionString = conn.ConnectionString;
      db.Open();
      return true;
   }
}

In the given example, the Initial Catalog and the timeout were changed without touch the original string.

I hope that this help you.

Upvotes: 25

Neil Thompson
Neil Thompson

Reputation: 6425

I think you will need a connection string for each database.

You have a drop down where the user selects which db to connect to. This value needs to be persisted, perhaps in the Session.

You need a class responsible for supplying a connection string value. This class gets passed the drop down value / pulls the value from the session, and returns the appropriate connection string to your DAL function

edit: if you have used the connection string name in all your pages you are going to have to change it. Encapsulate what might change. A search and replace might do it?

Upvotes: 1

Related Questions