如果输入的电子邮件/密码不正确,我希望显示一个消息框。我正在使用else语句,但如果登录不正确,则不显示该消息。
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
答案 0 :(得分:0)
reader.Read()
返回true;如果resultset为空,则返回false。在您的情况下,如果没有此类用户(使用提供的用户名和密码),程序将无法进入循环,并且无法访问If userFound = True
阻止。
所以,跳过while
循环并写下这样的东西:
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
修改强>
还有一件事:永远不要连接字符串来制作命令文本。相反,使用参数:
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)))