Reputation: 410
I'm having an issue that in testing, it is not working out. My code is for a button that checks whether or not a correct answer has been input. If the answer is correct, there's a message in the label; conversely, there's a message if it's wrong.
What I have in mind is to have a variable that checks if a wrong input has been entered "3 times" then have my code show that in the label. Here's what I have:
Private Sub btnAnswer_Click(sender As Object, e As EventArgs) Handles btnAnswer.Click
'Setup count variable to monitor wrong answer count.
Dim CounterWrong As Integer = 1
If (txtSpell.Text = "Bicycle") And (CounterVar = 0) Then
lblAnsResult.Text = "Correct!"
lblAnsResult.Show()
btnNext.Focus()
ElseIf (txtSpell.Text = "Table") And (CounterVar = 1) Then
lblAnsResult.Text = "Correct!"
lblAnsResult.Show()
btnNext.Focus()
ElseIf (txtSpell.Text = "Television") And (CounterVar = 2) Then
lblAnsResult.Text = "Correct!"
lblAnsResult.Show()
btnNext.Focus()
Else
CounterWrong += 1
txtSpell.Text = String.Empty
lblAnsResult.Text = "Wrong! Try Again..."
lblAnsResult.Show()
txtSpell.Text = Focus()
End If
While CounterWrong < 3
CounterWrong += 1
If CounterWrong = 5 Then
MessageBox.Show(CounterWrong)
End If
End While
End Sub
I tried to setup my little While
loop to see if my CounterWrong
variable is incrementing properly, but I can't think of how to set it up. I know each time I click the button, CounterWrong
is being set back to 1. Can someone set me in the right direction here? Thanks.
Upvotes: 0
Views: 4209
Reputation: 125
You could declare the variable on the form instead:
Public Class frmTest
'Setup count variable to monitor wrong answer count.
Dim CounterWrong As Integer = 1
Private Sub btnAnswer_Click(sender As Object, e As EventArgs) Handles btnAnswer.Click
If (txtSpell.Text = "Bicycle") And (CounterVar = 0) Then
lblAnsResult.Text = "Correct!"
lblAnsResult.Show()
btnNext.Focus()
ElseIf (txtSpell.Text = "Table") And (CounterVar = 1) Then
lblAnsResult.Text = "Correct!"
lblAnsResult.Show()
btnNext.Focus()
ElseIf (txtSpell.Text = "Television") And (CounterVar = 2) Then
lblAnsResult.Text = "Correct!"
lblAnsResult.Show()
btnNext.Focus()
Else
CounterWrong += 1
txtSpell.Text = String.Empty
lblAnsResult.Text = "Wrong! Try Again..."
lblAnsResult.Show()
txtSpell.Text = Focus()
End If
If CounterWrong = 5 Then
MessageBox.Show(CounterWrong)
End If
End Sub
End Class
Upvotes: 2
Reputation: 6542
Either change the counter to a VB 'Static' variable:
Static CounterWrong As Integer = 0
or use a class-level field:
Private CounterWrong As Integer = 0
VB 'Static' variables maintain state between method calls (C++ has a similar feature). Many would regard using a field as better practice.
I also changed them to be '0' initially - I think this makes more sense.
Upvotes: 2