Friday, 6 September 2013

How to Configure a Database Connection String in an Application you created in C# to make it run on other PC/other SQL Server


When you create an application, you usually embed the connection string in your application by doing something like this:










You have created your application and connected it to Database in your PC. Now, you want to run this application at some other PC having other SQL Server. So, you copy all the executable files from your PC and save them on other PC and run the application. You can find all these files in your bin folder:

The first file of type 'Application' is the main application executable file. Now when you will run this application on the other PC where you saved these files it will give you an error like 'An Unhandled Exception exception has occured. A network-related or instance-specific error occured while establishing a connection to SQL Server." This is because the Connection String you entered in your application was the Connection String of your SQL Server on your PC which may not be the same on other PC. So what You must do now?
The best way is to keep the Connection String in a Configurable file so that it can be configured anytime.

Steps to save Connection String in a Configurable file: Look at the pictures below:


If you have more than one project in same solution then add the Configuration File in each project separately.
Here I have two projects(ACW and Employee) in the same Solution(ACW). I will show you how to store Connection String in Configuration File in one project. You can perform the same steps to store Connection String in other projects and use it.



Click Add


Write the following code in above file:



Save it

You will see that App.config file is added to your project. Now use the following code wherever you have to use the Connection String in the code:

Now you don't have to worry about changing the Connection String on deploying your application on other PC/SQL Server. Just use the Configuration File and change the connection string there and you need not worry about changing at every place you used it. Look at the pictures below on how to do it:

You will find the CONFIG file in your bin folder





Save it.

END


Hope this post helped you.
Don't forget to leave your comments. Thank you.. :)

No comments:

Post a Comment