Write an ASP.Net program to connect to the master database in SQL Server in the Page_Load event. When the connection is established, the message ‘Connection has been established’ should be displayed in a label in the form. 

Answer:

Default.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="SqlConnectionExample.Default" %>

<!DOCTYPE html>
<html lang="en">
<head runat="server">
    <meta charset="utf-8" />
    <title>SQL Server Connection Test</title>
</head>
<body>
    <form id="form1" runat="server">
        <h2>SQL Server Connection Example</h2>
        <asp:Label ID="lbldisplay" runat="server" ForeColor="Blue" Font-Bold="True"></asp:Label>
    </form>
</body>
</html>

Default.aspx.cs

using System;
using System.Data.SqlClient;

namespace SqlConnectionExample
{
    public partial class Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string connectionString = "Server=YOUR_SERVER_NAME;Database=master;Integrated Security=True;";

            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                try
                {
                    connection.Open();
                    lbldisplay.Text = "Connection has been established.";
                }
                catch (Exception ex)
                {
                    lbldisplay.Text = "Error: " + ex.Message;
                }
            }
        }
    }
}
Scroll to Top