Monday, 22 April 2013

How to Use Web.config File For Database Connectivity in ASP.NET using C#


How to Use Web.config File For Database Connectivity in ASP.NET using C#


Web.config is present in your application by deafault. The main use of web.config file is to configure our ASP.NET web application. Web.config file is basically an XML document which contains configuration information about our web application. Web.config has many functions including information that controls module loading, session state configuration, security configuration and application language and compilation settings. One of most important advantage of Web.config file is its use in database connectivity. Giving code for databse connectivity on every page is very time consuming as well as it degrades the performance of our web application. To overcome this problem we can use Web.config file. Following are the steps to use web.config file for database connectivity :
Step 1: Open your web.config file by double clicking on it. After that add the code given in between <configuration></configuration>
that is:
<configuration>
<connectionStrings>
<add name=”connectionstring”
connectionString=”data source=.\SQLEXPRESS;Integrated Security=SSPI;
AttachDBFilename=|DataDirectory|\aspnetdb.mdf;User Instance=true”
providerName=”System.Data.SqlClient” />
</connectionStrings>
</configuration>
 where:
Connection name you may give according to your wish.
connectionString path is your path to your databse.
*Note:you can find Connection String path and providerName by right clicking on your database source and opening its properties.

Step 2: In your abc.aspx page add the namespace “using System.Configuration;”  and  “using System.Data.SqlClient;“.

Step 3: Add the following code in click event of your button:
string s = ConfigurationManager.ConnectionStrings["connectionstring"].ToString;
SqlConnection con = new SqlConnection();

Step 4: Rest of the steps are same for fetching, updating, deleting the data from the database.
If do not use web.config file for connectivity, you need to do the complete coding on the click event of each button which is very time consuming from programming point of view. Web.config thus helps a lot in code reduction because for the complete web application we can do database connectivity in one part only. After that all we need is to create a connection object and use it for further implementation. Web.config file is also used for many other implementations like authentication, session state configuration, etc.

No comments:

Post a Comment