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"?>
 <add name="SQLDbConnection" connectionString="Server=servername; Database=databasename; User Id=username; password=password" providerName="System.Data.SqlClient" />

Create the form :

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>
<!DOCTYPE html>
<html xmlns="">
<head runat="server">
    <title>ASP.NET SQL Server connection</title>
    <form id="form1" runat="server">
        <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>

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)

        lblconnectionresult.Text = "Database connected successfully.."
    End Sub
End Class

 Download source code:

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


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.