dotnetwarriors.com

Define Connection String in C# Code File in Asp.Net

Jul 22, 2018 Asp.net C# Sql Server 33
In this Article i will explain How to Define Connection String in C# Code File in Asp.Net Project.

First of all create a new web project and add a new web form with a button on it to check the connection to Sql server.

Write the below code in .aspx page to design the web form as shown below image:

 

Define Connection String in C# Code File in Asp.Net

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

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

Add the NameSpace using System.Data.SqlClient;

SqlConnection con;
        protected void Page_Load(object sender, EventArgs e)
        {
            con = new SqlConnection("Data Source=hello\\SQLEXPRESS;Initial Catalog=aspdotnetcorner;Integrated Security=True");
        }
        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);
            }
        }

 

In Above code “Data Source=hello\\SQLEXPRESS;Initial Catalog=aspdotnetcorner;Integrated Security=True” is the connection string to connect the database.

where Data Source is the Server Name, Initial Catalog Database Name, and Integrated Security where we define user credentials username and password.

 

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 C# Code 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 C# Code File in Asp.Net

 





Share This Article :

Comments


Add Comment


 
Security Code :
2 + 18 =