当我单击Button1时如何使变量保持工作状态? 有人可以帮我吗?
Public Class Form2
Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim Number As Integer
Randomize()
Number = Int(Rnd() * 10000000) + 1
Label2.Text = Number
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If TextBox1.Text = Number Then
MsgBox("Correct")
Else
MsgBox("Not Correct")
End If
End Sub
End Class
答案 0 :(得分:4)
获取您的变量并将其作为类变量移动。
Public Class Form2
Private Number As Integer ' <-----
Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Randomize()
Number = Int(Rnd() * 10000000) + 1
Label2.Text = Number
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If TextBox1.Text = Number Then
MsgBox("Correct")
Else
MsgBox("Not Correct")
End If
End Sub
End Class
以您的示例为例,这样做似乎很合理,但是我建议您不要过多地养成这样做的习惯。我见过人们几乎把所有东西都当作类变量。
另外,将Option Strict设为On。随着程序变得越来越复杂,它将在以后为您省去一些头痛。