简体   繁体   中英

Struggling with basic VB.net. Variable addition

I'm trying to set up my form program so if the user fails to login 3 times (linked to a database), it closes the program. However, I'm a kinda crap at programming and I can't get the variable to actually hold the addition I'm trying to use?

Private Sub Login_Click(sender As Object, e As EventArgs) Handles Login.Click
    Dim uname, pass As String
    Dim attempt As Integer = 0
    ' Warns the user if they have missed out login information.
    If UserNameBox.Text = "" Or PasswordBox.Text = "" Then
        MessageBox.Show("Please ensure you have entered your username and password", "Authentication Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
    Else
        uname = UserNameBox.Text
        pass = PasswordBox.Text
        GetFilteredData("username = '" & uname & "' AND password = '" & pass & "'")
        If CountRecords() = 1 Then
            MsgBox("Logged In!")
        Else
            MsgBox("Incorrect Credentials!")
            attempt = attempt + 1 ' <-- Main Issue is here
            If attempt = 4 Then
                Application.Exit()
            End If
        End If
    End If
End Sub

Any help would be amazing. Thanks :D

You're declaring on the attempt varible inside the Login_Click event handler. Hence, each time the Login_Click event is raised, you are initializing it to 0.

Dim attempt As Integer = 0

Try to move it to outer scope, for example make it a member of the Class.

This should work. If you want to have variable accessible from all subs, just take it out too root of class.

Private attempt As Integer = 0

Private Sub Login_Click(sender As Object, e As EventArgs) Handles Login.Click
Dim uname, pass As String

' Warns the user if they have missed out login information.
If UserNameBox.Text = "" Or PasswordBox.Text = "" Then
    MessageBox.Show("Please ensure you have entered your username and password", "Authentication Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
Else
    uname = UserNameBox.Text
    pass = PasswordBox.Text
    GetFilteredData("username = '" & uname & "' AND password = '" & pass & "'")
    If CountRecords() = 1 Then
        MsgBox("Logged In!")
    Else
        MsgBox("Incorrect Credentials!")
        attempt = attempt + 1 ' <-- Main Issue is here
        If attempt = 4 Then
            Application.Exit()
        End If
    End If
End If
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM