Search code examples
sqlvb.netconditional-statementsmessagebox

Button is not working when I used If/Else statement


I have a ComboBox for username and a TextBox for password. I'm trying to create the usual login form where in the user needs to input the correct username and password or else access is denied. MsgBox("Welcome") is working and MsgBox("Failed") is not.

Private Sub btnlogin_Click(sender As Object, e As EventArgs) Handles btnlogin.Click
    sSql = "Select * from tblusers where username = '" & cmbusers.Text & "' and password = '" & txtpass.Text & "'"
    execSQL(sSql, False)
    If RD.Read Then
        If cmbusers.Text = RD(1) And txtpass.Text = RD(2) Then
            MsgBox("Welcome")
        Else
            MsgBox("Failed", MsgBoxStyle.Critical)
        End If
    End If
End Sub

Solution

  • Your query won't return anything if the credentials aren't correct, Your messageBox Failed is in the wrong position as it will appear only if data was read.

    Private Sub btnlogin_Click(sender As Object, e As EventArgs) Handles btnlogin.Click
        sSql = "Select * from tblusers where username = '" & cmbusers.Text & "' and password = '" & txtpass.Text & "'"
        execSQL(sSql, False)
        If RD.Read Then
            If cmbusers.Text = RD(1) And txtpass.Text = RD(2) Then
                MsgBox("Welcome")
            End If
        Else
            MsgBox("Failed")
        End If
    End Sub