Home > ASP.NET > Getting ConnectionStrings value from code behind

Getting ConnectionStrings value from code behind

When you do wants to get some data from a database to show it on your ASP.NET web application, you will need to use a connection string to connect to the database. This string is very important because, at most conditions, you will be using this string again and again across the entire application. Therefore, you can utilize the ConnectionStrings tag in the web.config file to store your predefined connection strings.

Well, some programmers will say “Why do I need to store it in the web.config file? I can just code it in my code behind codes and it will still work the same.”. Yes, it will still work the same. But that is only suitable for a mini web application that does not require much connection to the database. However, if it’s a big web application and the connection string values have to be changed, the programmers will spend a long time just to find and replace the existing connection string to the new string.

Therefore, it’s advised to always store a connection string in the web.config file and get its value from here. Below, I will show you how to get the connection string values from the ConnectionStrings tag in the web.config file.


Code in web.config:

        <add name="MyConnectionString" connectionString="Your connection string here" providerName="System.Data.SqlClient" />

Code for C#:


Code for VB.NET:


From the sample above, I’ve named my connection string to “MyConnectionString”. For the connectionString values which I’ve written as “Your connection string here”, you will have to replace it with a proper connection string. You can find more about connection string from http://connectionstrings.com/. As for the providerName, you have to put the namespace of the data connection class. In this case above, “System.Data.SqlClient” will be connecting to Microsoft SQL Server.

  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: