Home > Mobile >  If my counter ends at 10 at textbox1(TB1) the random number won't show in my textbox2(TB2)
If my counter ends at 10 at textbox1(TB1) the random number won't show in my textbox2(TB2)

Time:01-29

If my counter ends at 10 at textbox1 (TB1) the random number won't show in my textbox2(TB2)

enter image description here

Public Class Form1

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

        If TB1.Text = 10 Then
            Dim num1 As Integer
            Dim randomnumber As New Random

            num1 = randomnumber.Next(100, 201)
            TB2.Text = num1
        End If
        Timer1.Enabled = True

    End Sub

    Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick

        TB1.Text = TB1.Text   1
        If TB1.Text = 10 Then
            Timer1.Enabled = False
        End If

    End Sub
End Class

CodePudding user response:

Use a numeric variable to keep the count, not the TextBox. The TextBox.Text property is of type String, not Integer!

Putting Option Strict On at the top of your code will enforce using proper types. VB by default allows you to loosely convert between integer and string, which is poor practice.

Option Strict On

Public Class Form1

    Private count As Integer

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        count = 0
        Timer1.Enabled = True
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

        If count = 10 Then
            Dim randomnumber As New Random()
            Dim num1 = randomnumber.Next(100, 201)
            TB2.Text = num1.ToString()
        End If
        Timer1.Enabled = True

    End Sub

    Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
        count  = 1
        Timer1.Enabled = count <> 10
        TB1.Text = count.ToString()
    End Sub

End Class

enter image description here

  •  Tags:  
  • Related