Jul 3, 2014

How to get connections string from web.config in Asp.Net

Set connection string in web.config file as below:

<connectionStrings >
 <add name ="connectiontodatabase" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True;User Instance=True" providerName="System.Data.SqlClient"/>
</connectionStrings>


for retrieving Connection String from web.config write as

Add System.Data.SqlClient and System.Configuration references to Your code. 



using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
using System.Xml;

namespace WebApplication2
{
 public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}
 protected void authenticationbutton_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection  ( ConfigurationManager.ConnectionStrings ["connectiontodatabase"].ConnectionString );
 con.Open();
Response.Write("<script> alert('Connection opend') </script>");
con.Close ();
}
}
}

No comments:

Post a Comment