Login Tutorial Using Access Database - Visual Basic .NET

Tags: VB.NET, VB 2008, VB 2010, VB 2012, VB 2013

In this tutorial, you will learn how to log in the user by checking the username and password stored in an Access database.

First create a table in Access database and call it users.

There are four fields in the users table:

ID, username, password, FirstName, LastName
users table in access database

Then add a sample record like I did in the following:

Now let's connect the program in Simple Login Tutorial to the database we created.

Add the following code above Public Class Form1

 Imports System.Data.OleDb

Then add the following declarations below Public Class Form1
	Dim provider As String
    Dim dataFile As String
    Dim connString As String
    Dim myConnection As OleDbConnection = New OleDbConnection

The following code is the Button1 click event:
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
        provider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source ="
        'Change the following to your access database location
        dataFile = "C:\Users\Jimmy\Documents\customers.accdb"
        connString = provider & dataFile
        myConnection.ConnectionString = connString

        'the query:
        Dim cmd As OleDbCommand = New OleDbCommand("SELECT * FROM [users] WHERE [username] = '" & TextBox1.Text & "' AND [password] = '" & TextBox2.Text & "'", myConnection)
        Dim dr As OleDbDataReader = cmd.ExecuteReader
        ' the following variable is hold true if user is found, and false if user is not found 
        Dim userFound As Boolean = False
        ' the following variables will hold the user first and last name if found.
        Dim FirstName As String = ""
        Dim LastName As String = ""

        'if found:
        While dr.Read
            userFound = True
            FirstName = dr("FirstName").ToString
            LastName = dr("LastName").ToString
        End While

        'checking the result
        If userFound = True Then
            Form2.Label1.Text = "Welcome " & FirstName & " " & LastName
            MsgBox("Sorry, username or password not found", MsgBoxStyle.OkOnly, "Invalid Login")
        End If
    End Sub

Share This

Home | About | Contact | Privacy Policy

Copyright visual-basic-tutorials.com 2018 - All Rights Reserved.