Aspdotnet-Suresh

aspdotnet-suresh offers C#.net articles and tutorials,csharp dot net,asp.net articles and tutorials,VB.NET Articles,Gridview articles,code examples of asp.net 2.0 /3.5,AJAX,SQL Server Articles,examples of .net technologies

Read or Write connection strings in web.config file using asp.net

Nov 27, 2011
Introduction:

In this article I will explain how to read or write connection strings in web.config file using asp.net.


Description:

In Previous article I explained clearly about Encrypt or Decrypt connection strings in web.config file using asp.net. Now I will explain how to write connection strings in web.config file and how to read connection strings from web.config file using asp.net. 

I have one web application that contains many pages and each page contains relationship with database connection to get data from database and display it on page because of that I need to write database connections for each page to interact with database. Now the server name or credentials of database server has changed in that situation it will create problem because we need to modify the database connections of each page using asp.net. 

To avoid this situation it would be better if we place connection string in one place and reuse it in every page wherever we need to connect to SQL Server. Web.config is the best place to store the connection strings in asp.net and it would be safer place to store the connection strings instead of writing connection strings in every web page.

Now we want to add connection string in web.config file for that first create new website using visual studio after that create new website open web.config file and search for “connectionStrings” and add new item in connectionStrings section

After open web.config file in application and add sample db connection in connectionStrings section like this 

<connectionStrings>
<add name="yourconnectinstringName" connectionString="Data Source= DatabaseServerName; Integrated Security=true;Initial Catalog= YourDatabaseName; uid=YourUserName; Password=yourpassword; " providerName="System.Data.SqlClient"/>
</connectionStrings >
Example of declaring connectionStrings in web.config file like this

<connectionStrings>
<add name="dbconnection" connectionString="Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB" providerName="System.Data.SqlClient"/>
</connectionStrings >
Here to access my database server there is no need of username and password for that reason I didn’t enter username and password in connection string.

After add dbconnection in connectionString we need to write the some code in our codebehind file to get connection string from web.config file for that add following namespace in codebehind file and write the following code

using System.Configuration;
 This namespace is used to get configuration section details from web.config file.

After add namespaces write the following code in code behind

C# code

using System;
using System.Data.SqlClient;
using System.Configuration;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{   
//Get connection string from web.config file
string strcon = ConfigurationManager.ConnectionStrings["dbconnection"].ConnectionString;
//create new sqlconnection and connection to database by using connection string from web.config file
SqlConnection con = new SqlConnection(strcon);
con.Open();
}
}
VB.NET

Imports System.Data.SqlClient
Imports System.Configuration
Partial Public Class _Default
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
'Get connection string from web.config file
Dim strcon As String = ConfigurationManager.ConnectionStrings("dbconnection").ConnectionString
'create new sqlconnection and connection to database by using connection string from web.config file
Dim con As New SqlConnection(strcon)
con.Open()
End Sub
End Class
Here we stored our database connection string in web.config file it was not secured if we want to encrypt the connection string in web.config file check this post encrypt or decrypt connection string in web.config file.

If you enjoyed this post, please support the blog below. It's FREE!

Get the latest Asp.net, C#.net, VB.NET, jQuery, Plugins & Code Snippets for FREE by subscribing to our Facebook, Twitter, RSS feed, or by email.

subscribe by rss Subscribe by RSS subscribe by email Subscribe by Email

18 comments :

krishna patel said...

Nice Blog and I am going to congratulate you to get higher traffic within your blog.There are a lot of information within your blog which is really helpful for worldwide developers and they can learn and also get a solution for their technical problem .

It is really good that you are giving extra time to maintaining the blog and give revert back answer to all world wide developer.

Best of luck for your upcoming career.
http://www.codeprojectdownload.com

Showne Prince said...

how can I connect multi Dababase server using this connection string?

Hetal said...

hello

i have MS access 2007 connection string

I use asp.net 2010 express adition

I right below code in my website

IN Recent_artical.aspx.cs file

String strCon = ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString;
OleDbConnection con = new OleDbConnection(strCon);
con.Open();

which code right in Web.config file

Please urgent answer in my gmail id
hetalmodi43@gmail.com

Anish yandrapragada said...

hi suresh its been very interesting by reading ur articles....

can u plz give me the clear difference of app settings and connection strings which one is better to use?

r they both same if not how they differ?

can u plz explain on this

Abhinavsingh993 said...

SPECIAL REQUEST CAN YOU GUIDE ME HOW TO CONNECT THE DATABASE IN ASP.NET WITH ORACLE

Anonymous said...

fhghjgjhgjhjhoikjahgdfsdgfbbbbb

Jmal Salih said...

very helpful code
thank you

Anonymous said...

pls tell if i want to use multiple connection string one for access and one for sql ..how can i achieve this

Anonymous said...
This comment has been removed by a blog administrator.
Anonymous said...
This comment has been removed by a blog administrator.
Sangam Malik said...

Nice article, your article are very help full........Thanks to you from bottom of my heart

veerendra said...

hi sir iam veerendra u r regular follower sir pls
help me i want remote database connection through
C# windows Applications

Anonymous said...

Very Nice article Sir.I really wants to thank you for such a nice explanation.

bhavyesh patel said...

can you say how many types of connection string available with asp.net and sql server combine...

Busa Krupali said...

Your code is very useful to beginner also.

Suhas Saravdekar said...

nice example for understanding. thank you

s.kantha samy said...

nice article brother it has helping me a lot!thanx bro

Anonymous said...

how to write namespaces in web config with that use we can't write namespaces for every page

Give your Valuable Comments

Other Related Posts

© 2010-2012 Aspdotnet-Suresh.com. All Rights Reserved.
The content is copyrighted to Suresh Dasari and may not be reproduced on other websites without permission from the owner.