How can I fix my timer algorithm problem?

0

I wish to find the problem of this code which gives that the application is in break mode Exception unhandled. What can I try?

System.InvalidOperationException occurred HResult=0x80131509 Message=An error occurred creating the form. See Exception.InnerException for details. The error >> > is: Object reference not set to an instance of an object. Inner Exception 1: NullReferenceException

Code:

Public Class Form1
    Dim h As Integer = 0, h2 As Integer = Val(TextBox1.Text)
    Dim m As Integer = 0, m2 As Integer = Val(TextBox2.Text)
    Dim s As Integer = 0, s2 As Integer = 60
    Dim m1 As Integer = 0, ml2 As Integer = 100

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Timer2.Start()
    End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        Timer2.Stop()
    End Sub

Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
        Timer2.Stop()
        h2 = Val(TextBox1.Text)
        m2 = Val(TextBox2.Text)
        s2 = 60
        ml2 = 100
        Label1.Text = h2 & " : " & m2 & " : " & s2 & " : " & ml2
    End Sub

Private Sub Timer2_Tick(sender As Object, e As EventArgs) Handles Timer2.Tick
        ml2 -= 1
        Label1.Text = h2 & " : " & m2 & " : " & s2 & " : " & ml2
        If ml2 = 0 Then
            ml2 = 100
            s2 -= 1
            Label1.Text = h2 & " : " & m2 & " : " & s2 & " : " & ml2
            If s2 = 0 Then
                s2 = 60
                m2 -= 1
                Label1.Text = h2 & " : " & m2 & " : " & s2 & " : " & ml2
                If m2 = 0 Then
                    m2 = 60
                    h2 -= 1
                    Label1.Text = h2 & " : " & m2 & " : " & s2 & " : " & ml2
                    If h2 = 0 Then
                        h2 = 0
                        Timer1.Stop()
                        h2 = Val(TextBox1.Text)
                        m2 = Val(TextBox2.Text)
                        s2 = 60
                        ml2 = 100
                        Label1.Text = h2 & " : " & m2 & " : " & s2 & " : " & ml2
                    End If
                End If
            End If
        End If
    End Sub
End Class
vb.net
timer
visual-studio-2017
asked on Stack Overflow May 20, 2020 by Immortality • edited May 21, 2020 by Immortality

1 Answer

0

You can not access value of TextBox1 before complete initialization. Just by tweak your code slightly, error goes away.

Dim h As Integer = 0, h2 As Integer = 0
Dim m As Integer = 0, m2 As Integer = 0
Dim s As Integer = 0, s2 As Integer = 60
Dim m1 As Integer = 0, ml2 As Integer = 100

Set h2 and m2 value at load event of form like as below:

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load       
    h2 = Val(TextBox1.Text)
    m2 = Val(TextBox2.Text)
End Sub
answered on Stack Overflow May 20, 2020 by Always_a_learner

User contributions licensed under CC BY-SA 3.0