Open the web.config file in application, add sample db connection in connectionStrings section as Mentioned Below:
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
- <connectionStrings>
- <add name="yourconnectinstringName" connectionString="Data Source= DatabaseServerName; Integrated Security=true;Initial Catalog= YourDatabaseName; uid=YourUserName; Password=yourpassword; " providerName="System.Data.SqlClient" />
- </connectionStrings>
Declaring connectionStrings in web.config file:
- <connectionStrings>
- <add name="dbcon" connectionString="Data Source=Peace4;Integrated Security=true;Initial Catalog=MyDB" providerName="System.Data.SqlClient" />
- </connectionStrings>
C# code
- using System;
- using System.Data.SqlClient;
- using System.Configuration;
- public partial class _Default: System.Web.UI.Page {
- protected void Page_Load(object sender, EventArgs e) {
- //Get connection string from web.config file
- string strcon = ConfigurationManager.ConnectionStrings["dbconnection"].ConnectionString;
- //create new sqlconnection and connection to database by using connection string from web.config file
- SqlConnection con = new SqlConnection(strcon);
- con.Open();
- }
- }
Comments
Post a Comment