【问题标题】:Integer not incrementing in VB整数在VB中不递增
【发布时间】:2016-07-19 19:46:06
【问题描述】:

我有以下代码,当用户第一次单击按钮时它执行 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

【问题讨论】:

  • 一边;您也许应该使用Boolean 而不是只会变为 1 的计数器,并且 if 和 else 之间的公共代码(总是这样做)应该在 If 块之外以避免重复

标签: vb.net if-statement counter


【解决方案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

【讨论】:

    【解决方案3】:

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

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

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

    感谢 Verdolino 指出这一点。

    希望我的回答对你有帮助!

    【讨论】:

    • 使用此按钮单击事件处理程序Private Sub btnTurn_Click(sender As System.Object, e As System.EventArgs) Handles btnTurn.Click,ByRef/ByVal 不适用。 SLaks 回顾了类级变量声明
    • 哦,是的,我完全忘记了,谢谢@Verdolino
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-13
    • 2022-11-19
    • 1970-01-01
    • 1970-01-01
    • 2017-05-05
    相关资源
    最近更新 更多