MSAccess login form

Viewed 86

I created a login form but realized that i can log in without entering a password. only a user name. what should i do so as to solve the problem

Option Compare Database
Option Explicit

Private Sub cmdlogin_Click()
    Dim rs As Recordset

    Set rs = CurrentDb.OpenRecordset("Account Details", dbOpenSnapshot, dbReadOnly)
    rs.FindFirst "UserName='" & Me.txtusername & "' "
    
    Me.lblusername.Visible = False
    If rs.NoMatch = True Then
        Me.lblusername.Visible = True
        Me.txtusername.SetFocus
        Exit Sub
    End If
    Me.lblpassword.Visible = False
    If rs!Password <> Me.txtpassword Then
        Me.lblpassword.Visible = True
        Me.txtpassword.SetFocus
        Exit Sub
    End If
      DoCmd.OpenForm "Dashboard"
      DoCmd.Close acForm, Me.Name
    
End Sub
1 Answers

If txtusername or txtpassword is Null the conditional will fail. Try:

rs.FindFirst "UserName='" & Nz(Me.txtusername,"") & "'"

If rs!Password <> Nz(Me.txtpassword, "") Then

Or consider:

    Dim rs As Recordset
    With Me
    .lblusername.Visible = False
    .lblpassword.Visible = False
    If IsNull(.txtusername) Or IsNull(.txtpassword) Then
        MsgBox "Enter username or password"
    Else
        Set rs = CurrentDb.OpenRecordset("SELECT UserName, Password FROM [Account Details] " & _
             "WHERE UserName='" & .txtusername & "'", dbOpenSnapshot, dbReadOnly)
        If Not rs.BOF And Not rs.EOF Then
            If rs!Password <> .txtpassword Then
                .lblpassword.Visible = True
                .txtpassword.SetFocus
            Else
                DoCmd.OpenForm "Dashboard"
                DoCmd.Close acForm, .Name
            End If
        Else
            .lblusername.Visible = True    
            .txtusername.SetFocus
        End If
    End If
    End With
Related