Easy Code for LoginPage in Vb.net Using Oledb Connection

Here is the walkthrough:

1)  e.g. MS Access Database file myDB.mdb contains a Users table with the following two fields:

Field Name   Data Type

Username     Text

Password      Text

2)  Create a new Windows Forms application, then add a “Login Form” template:

Project menu-> Add Windows Form -> Select “Login Form” template

3)  Code sample

Prerequisites: txtUsername TextBox, txtPassword TextBox, OK button and Cancel button on Login Form.

Imports System.Data.OleDb
Public Class LoginForm1
    ' OK button   
    Private Sub OK_Click(ByVal sender As System.Object, _
                   ByVal e As System.EventArgs) Handles OK.Click
        Dim con As New OleDbConnection("Provider=Microsoft.jet.oledb.4.0;data source=D:\myDB.mdb")
        Dim cmd As OleDbCommand = New OleDbCommand( _
                   "SELECT * FROM Users WHERE Username = '" & _
                   txtUsername.Text & "' AND [Password] = '" & txtPassword.Text & "' ", con)
        con.Open()
        Dim sdr As OleDbDataReader = cmd.ExecuteReader()
        ' If the record can be queried, it means passing verification, then open another form.   
        If (sdr.Read() = True) Then
            MessageBox.Show("The user is valid!")
            Dim mainForm As New MainForm
            mainForm.Show()
            Me.Hide()
        Else
            MessageBox.Show("Invalid username or password!")
        End If
    End Sub
    ' Cancel button   
    Private Sub Cancel_Click(ByVal sender As System.Object, _
                    ByVal e As System.EventArgs) Handles Cancel.Click
        Me.Close()
    End Sub
End Class

Leave a comment

Filed under .Net

Leave a comment