Not able to show error message if the email/passwo

2020-05-09 23:16发布

问题:

I want a message box to appear if the email/ password is entered incorrectly. I am using an else statement but it doesn't display the message if the login is incorrect.

MyConn = New OleDbConnection 
        MyConn.ConnectionString = connString 
        MyConn.Open() 

        str1 = ("SELECT * FROM [UserData] WHERE [Username] = '" & TxtUserName.Text & "' AND [Password] = '" & TxtPassword.Text & "'") 
        Dim cmd1 As OleDbCommand = New OleDbCommand(str1, MyConn)
        dr = cmd1.ExecuteReader 
        While dr.Read() 
            userFound = True 
            TxtPassword.Text = dr("Username").ToString 
            TxtUserName.Text = dr("Password").ToString 
            FirstNameToPass = dr("First Name").ToString 
            LastNameToPass = dr("Last Name").ToString 
            AddressToPass = dr("Address").ToString 
            EmailToPass = dr("Email").ToString 
            If userFound = True Then
                UserAccountView.Show() 
                Me.Hide() 
                TxtPassword.Clear() 
                TxtUserName.Clear() 
            Else
                MsgBox("Login is incorrect")
            End If
        End While
        MyConn.Close() 
    End If

回答1:

reader.Read() returns true if row exists or false if resultset is empty. In your case, if there is no such user (with provided username and password), program won't enter loop and it won't reach If userFound = True block.

So, skip while loop and write something like this:

If dr.HasRows
    dr.Read()
    TxtPassword.Text = dr("Username").ToString 
    TxtUserName.Text = dr("Password").ToString 
    FirstNameToPass = dr("First Name").ToString 
    LastNameToPass = dr("Last Name").ToString 
    AddressToPass = dr("Address").ToString 
    EmailToPass = dr("Email").ToString 

    UserAccountView.Show() 
    Me.Hide() 
    TxtPassword.Clear() 
    TxtUserName.Clear() 
Else
    MsgBox("Login is incorrect")
End If

edit:

one more thing: NEVER concatenate strings to make command text. Instead, use paramters:

str1 = ("SELECT * FROM [UserData] WHERE [Username] = ? AND [Password] = ?") 
Dim cmd1 As OleDbCommand = New OleDbCommand(str1, MyConn)
cmd1.Parameters.Add(New OleDbParameter("Username", CType(TxtUserName.Text, String))) 
cmd1.Parameters.Add(New OleDbParameter("Password", CType(TxtPassword.Text, String)))