Skip to main content

Open the web.config file in application, add sample db connection in connectionStrings    section as Mentioned Below:


  1. <connectionStrings>  
  2.     <add name="yourconnectinstringName" connectionString="Data Source= DatabaseServerName; Integrated Security=true;Initial Catalog= YourDatabaseName; uid=YourUserName; Password=yourpassword; " providerName="System.Data.SqlClient" />   
  3. </connectionStrings>  



Declaring connectionStrings in web.config file:



  1. <connectionStrings>  
  2.     <add name="dbcon" connectionString="Data Source=Peace4;Integrated Security=true;Initial Catalog=MyDB" providerName="System.Data.SqlClient" />   
  3. </connectionStrings>  


Now, write the code to get the connection string from web.config file in our codebehind file. Add the following namespace in codebehind file.

C# code


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



Comments