This article will explain How to connect database in ASP.NET. Here we connect sql database from ASP.NET. Using ADO.NET you can connect to SQL server. Connection object needs the necessary informations like server name, database name, username, password, etc.

Put this connection string in Web.Config. Kindly replace with SQL Server name, Database name, Username and password:

 
<?xml version="1.0"?>
<configuration>
 <connectionStrings>
 <add name="SQLDbConnection" connectionString="Server=servername; Database=databasename; User Id=username; password=password" providerName="System.Data.SqlClient" />
 </connectionStrings>
</configuration>

Create the form :

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>ASP.NET SQL Server connection</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Button ID="btnconnection" runat="server" Text="Connect to database" />
        <br />
        <asp:Label ID="lblconnectionresult" runat="server" Font-Size="Larger" Text="Check connection"></asp:Label>
    </div>
    </form>
</body>
</html>

VB code in the onclick event:

Imports System.Data
Imports System.Configuration
Imports System.Data.SqlClient

Partial Class _Default
    Inherits System.Web.UI.Page

    Protected Sub btnconnection_Click(sender As Object, e As EventArgs) Handles btnconnection.Click
        Dim connectionString As String
        Dim connection As SqlConnection
        connectionString = ConfigurationManager.ConnectionStrings("SQLDbConnection").ToString
        connection = New SqlConnection(connectionString)

        connection.Open()
        lblconnectionresult.Text = "Database connected successfully.."
        connection.Close()
    End Sub
End Class

 Download source code:

[wpdm_file id=8 template=”facebook ” ] 🔥104 Views

Anu

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.