1

我的程序有一个登录表单,它工作正常,但是当我输入不在我的数据库中的用户名和密码时,用户名和密码的文本框只会清除文本,并且不会显示显示“用户名不正确/密码”

这是我的代码:

 Dim con As OleDbConnection = New OleDbConnection( _
               "Provider=Microsoft.Jet.OLEDB.4.0;Data Source= UserPass.mdb;")
    con.Open()
    Dim str As String
    str = "SELECT * FROM UserPass WHERE Username='" & txtUsername.Text & "' AND Password='" & txtPassword.Text & "'"
    Dim cmd As OleDbCommand = New OleDbCommand(str, con)
    cmd.Parameters.AddWithValue("user", txtUsername.Text)
    cmd.Parameters.AddWithValue("pass", txtPassword.Text)
    Dim sdr As OleDbDataReader = cmd.ExecuteReader()
    ' It will be case sensitive if you compare usernames here.   
    If sdr.HasRows Then
        If sdr.Read Then
            If txtPassword.Text <> sdr("Password").ToString Or txtUsername.Text <> sdr("Username").ToString Then
                MessageBox.Show(" Incorrect Username/Password. Login Denied ", " Error! ", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Else
                MessageBox.Show(" You are now Logged In! ", " Welcome! ", MessageBoxButtons.OK, MessageBoxIcon.Asterisk)
                frmOne.Show()
                Me.Hide()
            End If
        End If
    End If

当我输入不在我的数据库中的用户名和密码时,如何让我的程序显示一个消息框?

4

2 回答 2

3

Line sdr.HasRows 看起来不会触发。如果用户名和密码不匹配,则在您的选择语句中不会有行。

考虑将代码更改为:

If sdr.HasRows Then
    If sdr.Read Then
            MessageBox.Show(" You are now Logged In! ", " Welcome! ", MessageBoxButtons.OK, MessageBoxIcon.Asterisk)
            frmOne.Show()
            Me.Hide()
    End If
Else
    MessageBox.Show(" Incorrect Username/Password. Login Denied ", " Error! ", MessageBoxButtons.OK, MessageBoxIcon.Error)
End If
于 2012-12-02T01:34:05.900 回答
1

看看这是否适合您,它使用的是 DMudge 向您展示的方法,但添加了案例检查。如果可行,请接受他的回答。

If sdr.HasRows Then
    If sdr.Read Then
        If txtPassword.Text <> sdr("Password").ToString Or txtUsername.Text <> sdr("Username").ToString Then
            MessageBox.Show(" Incorrect Username/Password. Login Denied ", " Error! ", MessageBoxButtons.OK, MessageBoxIcon.Error)
        Else
            MessageBox.Show(" You are now Logged In! ", " Welcome! ", MessageBoxButtons.OK, MessageBoxIcon.Asterisk)
            frmOne.Show()
            Me.Hide()
        End If
    End If
Else
    MessageBox.Show(" Incorrect Username/Password. Login Denied ", " Error! ", MessageBoxButtons.OK, MessageBoxIcon.Error)
End If
于 2012-12-02T02:36:44.840 回答