dotnetwarriors.com

Define Connection String in Web.Config File in Asp.Net

Jul 24, 2018 Asp.net C# Sql Server 31
In this Article i will explain how to Define Connection String in Web.Config File in Asp.Net and how to use them in Asp.Net Project/Website without writing connection string in every page.

lets design a simple form with a test button to test the SQL connection.

 

Define Connection String in Web.Config File in Asp.Net

To design the above form write the below code to .aspx page

<form id="form1" runat="server"><br /><br />
    <div>
    <asp:Button ID="btn1" runat="server" Text="Test Connection String" OnClick="btn1_Click" /></div>
        
    </form>

 

and write the below connection string in web.config file in <configuration> section

Change the connection string instances as yours.

<connectionStrings>
    <add name="constr" connectionString="Data Source=hello\SQLEXPRESS;Initial Catalog=aspdotnetcorner;Integrated Security=True"/>
  </connectionStrings>

in above code we can take any name is the

write the below code in .aspx.cs file to use the connection string and to handle the button click event :

Add the NameSpace using System.Data.SqlClient; and using System.Configuration;

 

SqlConnection con;
        protected void Page_Load(object sender, EventArgs e)
        {
            con=new SqlConnection(ConfigurationManager.ConnectionStrings["constr"].ConnectionString);
         
        }
        protected void btn1_Click(object sender, EventArgs e)
        {
            try
            {
                con.Open();
                ScriptManager.RegisterStartupScript(this, this.GetType(), "script", "alert('Connection Test Pass');", true);
                con.Close();
            }
            catch
            {
                ScriptManager.RegisterStartupScript(this, this.GetType(), "script", "alert('Connection Test Failed');", true);
            }
        }

Run the code with Ctrl+F5 or F5 and click on the button to test the connection,

if there is no error in connection string then a popup window will be display with message define in code “Connection Test Pass” like as below image:

 

Define Connection String in Web.Config File in Asp.Net

and if there is any error in connection string then a popup window will be display with message define in code “Connection Test Failed” like as below image:

 

Define Connection String in Web.Config File in Asp.Net

 





Share This Article :

Comments


Add Comment


 
Security Code :
8 + 5 =