Vous êtes sur la page 1sur 2

How do I create a Login Verification routine (Login Form) and make

the password case sensitive?

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

Note: The password in the TextBox is not case sensitive in the above code sample.

To make the password case sensitive, try this workaround:


First retrieve the password from database into DataReader object, and then compare it with
txtPassword.Text outside T-SQL statement.

Imports System.Data.OleDb
Public Class LoginForm1
Private Sub OK_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles OK.Click
Dim con As OleDbConnection = 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()
' It will be case sensitive if you compare passwords here.
If sdr("Password") <> txtPassword.Text.ToString() Then
MessageBox.Show("Invalid password!")
End If
sdr.Close()
con.Close()
End Sub
End Class

Vous aimerez peut-être aussi