整数不在VB中递增

时间:2016-07-19 19:46:06

标签: vb.net if-statement counter

我有以下代码,当用户第一次点击按钮时,它会执行if,然后第二次执行其他操作。除非它没有递增并做其他事情。

我试过了

count = count + 1

count = 1

计数+ = 1

我的代码在

下面
 'new button calls second survey page and sets mode to data
    Private Sub btnTurn_Click(sender As System.Object, e As System.EventArgs) Handles btnTurn.Click
        Dim count As Integer
        If count = 0 Then
            frmSurvey2.szCaller = "frmSurvey"
            frmSurvey2.szMode = "data"
            frmSurvey2.Show()
            count += 1
        Else
            frmSurvey2.szCaller = "frmSurvey"
            frmSurvey2.szMode = "print"
            frmSurvey2.Show()
        End If
    End Sub

3 个答案:

答案 0 :(得分:4)

每次调用此功能时都有一个单独的变量 因此,它始终为零。

您需要在课堂上声明。

答案 1 :(得分:2)

如果要维护变量的词法范围,请使用vb.net的Static

Private Sub btnTurn_Click(sender As System.Object, e As System.EventArgs) Handles btnTurn.Click
    Static count As Integer = 0
    If count = 0 Then
        ' do whatever
        count += 1
    Else
        ' do whatever else
    End If
End Sub

反过来,你可以在另一个处理程序中有另一个count,它不会与第一个处理程序发生碰撞。

Private Sub btnOther_Click(sender As System.Object, e As System.EventArgs) Handles btnOther.Click
    Static count As Integer = 0
    If count = 0 Then
        ' do whatever
        count += 1
    Else
        ' do whatever else
    End If
End Sub

答案 2 :(得分:-1)

正如其他人所说,每次调用按钮点击程序时,计数都会重置为零(注释后的第二行代码)。 当您对变量进行Dim时,它会自动将变量设置为0或Nothing。

要解决此问题,您可以尝试将按钮单击过程之外的计数声明为全局变量。

编辑:你不能在这里使用Byref和Byval。

感谢Verdolino指出这一点。

我希望我的回答有所帮助!