Single connection string across ASP.NET website
Tuesday, August 20, 2019

Beginner usually repeat a lot of code while developing any .NET project whether it is website or windows software.

Repetitive code causes maintenance problem i.e. you need to make changes at multiple places wherever code has been used. So it become very crucial to avoid duplicate code for ease of maintenance.

In this tutorial we will see how to place connection string at place and use across the project. Every project has a web.config file which is used to keep common things throughout application.

Here is the web.config code

<add name="Connection1" connectionString="Data Source=localhost;Initial Catalog=db_name;User Id=username;Password=secret_code" providerName="Sql.Data.SqlClient"/>

Add this code in <configuration></configuration> block.

Connection String from the Web.config can now be easily accessed in any web page.

How to Access connection string from web.config

SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["Connection1"].ConnectionString.ToString());

Connection is available and can now be used for read/write operation.