ADO Net Database ASP.Net Tutorial

File: Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="ConnectionTester" %>



    Untitled Page


    
    

                                 runat="server" 
                         Text="Use SQL Authentication (with sa account)" 
                         GroupName="Authentication" 
                         >
                         
    
                         runat="server" 
                     Text="Use Windows Integrated Authentication" 
                     GroupName="Authentication" 
                     Checked="True">
        
    
                    runat="server" 
                Text="Connect" 
                onclick="cmdConnect_Click">
    
        
    
    

    


File: Default.aspx.cs
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Web.Configuration;
using System.Data.SqlClient;
public partial class ConnectionTester : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
    }
    protected void cmdConnect_Click(object sender, EventArgs e)
    {
        string connectionString = "Data Source=localhost\\SQLEXPRESS;Initial Catalog=Pubs;";
        if (optWindows.Checked)
        {
            connectionString += "Integrated Security=SSPI";
        }
        else
        {
            connectionString += "User ID=sa";
        }
        SqlConnection myConnection = new SqlConnection(connectionString);
        try
        {
            myConnection.Open();
            lblInfo.Text = "Server Version: " + myConnection.ServerVersion;
            lblInfo.Text += "Connection Is: " + myConnection.State.ToString();
        }
        catch (Exception err)
        {
            lblInfo.Text = "Error reading the database. ";
            lblInfo.Text += err.Message;
        }
        finally
        {
            myConnection.Close();
            lblInfo.Text += "Now Connection Is: ";
            lblInfo.Text += myConnection.State.ToString();
        }
    }
}