There's something out there in life that will delight and amaze you.
Get up, get moving, and go find out what it is. - (Ralph Marston)

Friday, August 11, 2006

Accessing the ConnectionString in ASP.NET 2.0

It is a general practise; we define the connection string in the web.config file and access it from else where of the application when we need to handle database activities. In 1.1 and lower versions; in web.config file we define the connection string by specifying it as a key value pair tag under the . That is, we specify the connection details under the section of application settings. Just to recap, this is the way we’ve been using in normally.

 And access the connection string as follows. string ConnectionString = Configuration.AppSettings[“ConnectionString”].ToString(); The asp.net2.0 takes a one step forward and changes this by adding a tag just after the . So with in this we can specify any amounts of connections to the database. It will look as follows. Let’s see how we can do it in 2.0.

This is how we could access this connection defined in the web.config file. string strCon = ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString; The 2.0 uses the ConfigurationManager class which exposes the property of ConnnectionStrings where we could specify the key and access the connection string. If we want to get the application settings we could use the ConfigurationManager.AppSettings where this will give us the application settings of the web application.

Inorder to access the ConfigurationManager class we need to add the System.Configuration dll manually.

As you’ve seen now; ConfigurationManager class which is a new introduction in 2.0 allows us to carry out the general tasks in a bit different way; but guess; it’s trying to put things in to right places. Is it?


Post a Comment

<< Home