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

25 comments :

krishna patel said...
This comment has been removed by a blog administrator.
Unknown 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

Unknown 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

Unknown 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 dhaduk said...

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

Unknown said...

Your code is very useful to beginner also.

Unknown said...

nice example for understanding. thank you

Unknown 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

Anonymous said...

I need a help for Locking the User Account in Asp.Net Can u Guide Please

Anonymous said...

Thanks a lot for help people like me

Anonymous said...

how we find the connection strings path

Unknown said...

hello sir i hosting my website but is see the error 500 - Internal server error.
using web.config file please help me

anils said...

I use asp.net 2005 and database SQL server management studio 2005 but the problem is when I run my web application through virtual directory its display an error
"Cannot open database "website1" requested by the login. The login failed.Login failed for user 'server name'."
Somebody suggest me for this problem

Anonymous said...

Inspro Calendar Report

Anonymous said...

Your code is very useful
Thank You

Give your Valuable Comments

Note: Only a member of this blog may post a comment.

© 2015 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.