用户名和密码不正确时显示消息框

时间:2012-12-02 01:30:20

标签: vb.net winforms passwords username

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

这是我的代码:

 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

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

2 个答案:

答案 0 :(得分:3)

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

考虑将代码更改为:

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

答案 1 :(得分: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