Click here to Skip to main content
15,885,767 members
Articles / Database Development / SQL Server / SQL Server 2008
Article

How to change ConnectionString easily

Rate me:
Please Sign up or sign in to vote.
3.20/5 (10 votes)
6 Feb 2010CPOL2 min read 52.4K   17   11
Changing ConnectionString like an attribute in C#

Introduction

Everyone who starts a real project in the field of DataBase faces to the ConnectionString changing trouble. For small projects that it is not needed to alter the database location, changing the ConnectionString is not a problem, but in bigger projects specially in the time of application packaging, ConnectionString is a headache.

I have searched for a simple way for changing the ConnectionString in RUN TIME. There are many tips and tricks in Internet, but every way has a side effect.

In this article I will show you how you can change the ConnectionString in Run Time like an ordinary attribute.

Using the code

In .Net programming usually we do not alter the Settings class. This class holds the read only attributes of connection strings. By a magic we can change the connection string in Settings class.

Firstly, we create a User Scoped string Attribute in Settings class: 

[global::System.Configuration.UserScopedSettingAttribute()]
public string ConnectionString
{
    get { return (string)this["ConnectionString"]; }
    set { this["ConnectionString"] = value; }
}
This attribute holds the connection string in run time. There are some events that can be utilized for changing the main connection string, PropertyChanged and SettingsLoaded. PropertyChanged fires every time the value of any attribute in the class is changed, and SettingsLoaded fires when the loading process of the program settings is finished. We make two event handlers in the constructor of Settings class. Please note that there is no constructor and the constructor should be coded too.
public Settings()
{
    this.PropertyChanged += 
      new System.ComponentModel.PropertyChangedEventHandler(this.Settings_PropertyChanged);
    this.SettingsLoaded += 
      new System.Configuration.SettingsLoadedEventHandler(this.Settings_SettingsLoaded);
}
Also, we create two handlers:
private void Settings_PropertyChanged(System.Object sender,
         System.ComponentModel.PropertyChangedEventArgs e)
{
    if (e.PropertyName == "ConnectionString")
    {
        this["Original_ConnectionString"] = this.ConnectionString;
    }
}

private void Settings_SettingsLoaded(System.Object sender,
        System.Configuration.SettingsLoadedEventArgs e)
{
    // Advanced codes for post loading process...
}
The Original_ConnectionString is the main connection string of your program that you want to change it. Now every where in your code you can assign a new connection string to ConnectionString and it will be your new connection string. Also, you can define a function to do the job. A good place for defining the function is in Program class. You can use a function like this:
public static void ChangeConnectionString(string connectionstring)
{
    global::[project_namespace].Properties.Settings.Default.ConnectionString = 
        connectionstring;
}
By calling the function and passing the connection string to it, you can change the connection string easily. That's it!!!

Points of Interest

You can do more and you can have more flexible code if you use SettingsLoaded. I leave you with them alone!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) AMD
Canada Canada
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionVery good, thank you Pin
Member 1113048629-Nov-16 1:31
Member 1113048629-Nov-16 1:31 
QuestionUseful Pin
Olcay Akgün11-Jun-16 19:08
Olcay Akgün11-Jun-16 19:08 
QuestionHow use it ? Pin
MVictorL20-Nov-12 1:51
MVictorL20-Nov-12 1:51 
QuestionThank You Pin
haikal satria6-Jun-12 23:47
haikal satria6-Jun-12 23:47 
Generalhelp full - have 5 Pin
Pranay Rana30-Jan-11 18:52
professionalPranay Rana30-Jan-11 18:52 
Generalmy score of 4 Pin
manzo867-Feb-10 21:35
manzo867-Feb-10 21:35 
GeneralMy vote of 1 Pin
AntounPG6-Feb-10 23:24
AntounPG6-Feb-10 23:24 
GeneralRe: My vote of 1 Pin
Ali Marzban7-Feb-10 0:55
Ali Marzban7-Feb-10 0:55 
GeneralMy vote of 1 Pin
babakzawari6-Feb-10 22:49
babakzawari6-Feb-10 22:49 
GeneralMy vote of 1 Pin
Hamed J.I6-Feb-10 19:27
Hamed J.I6-Feb-10 19:27 
GeneralRe: My vote of 1 Pin
db_developer6-Feb-10 19:47
db_developer6-Feb-10 19:47 
Yes. it is headache when you have to use several providers to database and several classes to connect to db (I mean ADO.Net, ADOMD.Net, SMO, AMO, XmlClient). The bigest nuisance is that different providers support different connection string tokens for the same things. So I had to write class that uses their 'common connection string language' with provider-specific connection stirngs (ConnectionStringXxx, where Xxx is AMO for instance)

...this is off-top, but this is my sore... Wink | ;)

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.