整数不递增 VB

Integer not incrementing in VB

我有以下代码,当用户第一次点击按钮时它执行 if,然后第二次它执行 else。除了它不递增并执行其他操作。

我试过了

计数 = 计数 + 1

计数 = 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

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

您需要在 class 中声明。

如果您想保持变量的词法作用域,请使用 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

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

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

编辑:您不能在此处使用 Byref 和 Byval。

感谢 Verdolino 指出这一点。

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