Tuesday, August 13, 2013

ASP.NET Read Database Connection Strings from the Web.config File

This example reads a connection string from a Web.config file.

Add Below Code lines in Web.Config File under <configuration> tag


<appSettings>
    <add key="conn" value="Data Source=WIN-OOYB15IDNT4\MSSQLSERVER1;Initial Catalog=infodb; user id=sa;password=password@789"/>
</appSettings>

Code Behind to Access Connection string C#:

Add two namespace in Code behind:

using System.Data.SqlClient;

using System.Configuration;


Code in Page Load event: 


protected void Page_Load(object sender, EventArgs e)
{
   try
   {
       SqlConnection conn = new SqlConnection(ConfigurationManager.AppSettings["conn"]);
       conn.Open();
       //your ADO.NET code goes here
       Response.Write("Connection Opened Successfully...!!!");
       conn.Close();
    }
    catch (Exception ex)
    {
            Response.Write(ex.ToString());
    }
 } 

No comments:

Post a Comment

http://myaspdotnetworld.blogspot.com