This example provides you have an access database with a table named USERS having fields USERID and PASSWORD in it. Also you must have a connection string to your database.
In your main form you will need to call frmLogin:
vb Code:
Private Sub btnLogin_Click(ByVal sender As System.Object, ByVal As System.EventArgs) Handles btnLogin.Click
Dim frm As New frmLogin
Dim ret As DialogResult = frm.ShowDialog()
If ret <> Windows.Forms.DialogResult.OK Then
MsgBox("Login failed", MsgBoxStyle.Exclamation)
Else
' Logged in
End If
End Sub
Now you should create a frmLogin having txtLogin and txtPassword (textboxes) and btnLogin (a button):
vb Code:
Private Sub btnLogin_Click(ByVal sender As System.Object, ByVal As System.EventArgs) Handles btnLogin.Click
' Create a connection to your database:
Dim conn As New OleDbConnection("your connection string goes here")
' Create a query string (with parameters):
Dim sql As String = "SELECT USERID FROM USERS WHERE USERID=@p_userid AND PASSWORD=@p_passw;"
Dim cmd As New OleDbCommand(sql, conn)
' Add parameters
With cmd
.Parameters.AddWithValue("p_userid", txtLogin.Text)
.Parameters.AddWithValue("p_passw", txtPassword.Text)
End With
' Open your connection and perform the query
Try
conn.Open()
Dim usr As String = cmd.ExecuteScalar.ToString
If Not (IsDBNull(usr)) AndAlso usr = txtLogin.Text Then
Me.DialogResult = Windows.Forms.DialogResult.OK ' Return OK (user is found password matches)
Else
Me.DialogResult = Windows.Forms.DialogResult.Cancel ' Return Cancel (query returned nothing)
End If
Catch ex As Exception
' Catch database connection or query errors:
MsgBox("Could not connect to database or database error." & Environment.NewLine &
"Error message:" & ex.Message)
Me.DialogResult = Windows.Forms.DialogResult.Cancel
Finally
' Close connection
conn.Close()
Me.Close()
End Try
This is a very simple mechanism which provides almost no security at all since usernames and passwords are stored in unencrypted forms and the database itself can be compromised.