How to call connection string from Web.config In ASP.Net

 ASP.NET has a couple new ways to reference connection strings stored in the web.config or machine.config file.

<connectionStrings>
   <add name="LocalSqlServer" connectionString="data source=.\SQLEXPRESS; Initial Catelog="example" Integrated Security=true" providerName="System.Data.SqlClient"   />
</connectionStrings>

Easiest way to create connectiong string is to drag and drop one of your tables from the database to the page - connection string will be generated automatically. And you can call it like this:

using System.Configuration;

string conString = ConfigurationManager.ConnectionStrings["ConnectionStringName"].ConnectionString;
SqlConnection conn = new SqlConnection(conString);
conn.Open();


the another method is using AppSettings,

In Web.config

<configuration>

  <appSettings>

     <add key="ConnectionString"

          value="server=localhost;uid=sa;pwd=;database=DBPerson" />

  </appSettings>

</configuration>



ASPX Code Behind (aspx.cs)

using System.Configuration;

string connectionString = (string )ConfigurationSettings.AppSettings["ConnectionString"];
        SqlConnection conn = new SqlConnection(conString);
        conn.Open();

No comments:

Post a Comment