如何将一次单击产生的变量传递给另一次单击的功能?

时间:2019-02-22 15:29:24

标签: vb.net

我是Visual Basic的新手,当时正在Visual Basic上设计一个基本的计算器应用程序,我需要将先前计算的结果传递到另一次单击按钮的操作中。看起来是这样的:

计算器视图

enter image description here

代码如下:

Public Class Form1
Private Sub btnMultiply_Click(sender As Object, e As EventArgs) Handles btnMultiply.Click
    'varialbles
    Dim decNum1 As Decimal
    Dim decNum2 As Decimal
    Dim decResult As Decimal

    'Operation
    decNum1 = txtNum1.Text
    decNum2 = txtNum2.Text
    decResult = decNum1 * decNum2

    'Output
    lblResult.Text = decResult

End Sub

Private Sub btn20perc_Click(sender As Object, e As EventArgs) Handles btn20perc.Click
    Dim dec20perc As Decimal

    dec20perc = .2 * decResult <----- How do I pass it here, it gives an error obviously, but how do I solve this
End Sub
End Class

现在,在用户将两个数字相乘之后,我想获得结果的20%,但是如何将变量decResult传递给btn20perc_Click函数。 正确的方法是什么?

1 个答案:

答案 0 :(得分:0)

您需要在表单中设置一个全局变量以保存单击的第一个按钮的值:

Public Class Form1
    Private decResult As Decimal = 0.0

    Private Sub btnMultiply_Click(sender As Object, e As EventArgs) Handles btnMultiply.Click
        'varialbles
        Dim decNum1 As Decimal
        Dim decNum2 As Decimal

        'Operation
        decNum1 = txtNum1.Text
        decNum2 = txtNum2.Text
        Me.decResult = decNum1 * decNum2

        'Output
        lblResult.Text = Me.decResult
    End Sub

    Private Sub btn20perc_Click(sender As Object, e As EventArgs) Handles btn20perc.Click
        Dim dec20perc As Decimal
        dec20perc = .2 * Me.decResult

        'TODO - don't forget to output the result
    End Sub
End Class

除了使用全局变量,您还可以使用lblResult的内容:

Public Class Form1
    Private Sub btnMultiply_Click(sender As Object, e As EventArgs) Handles btnMultiply.Click
        'varialbles
        Dim decNum1 As Decimal
        Dim decNum2 As Decimal
        Dim decResult As Decimal

        'Operation
        decNum1 = txtNum1.Text
        decNum2 = txtNum2.Text
        decResult = decNum1 * decNum2

        'Output
        lblResult.Text = decResult
    End Sub

    Private Sub btn20perc_Click(sender As Object, e As EventArgs) Handles btn20perc.Click
        Dim dec20perc As Decimal

        If IsNumeric(lblResult.Text) Then
            dec20perc = .2 * CDec(lblResult.Text)
        End If

        'TODO - don't forget to output the result
    End Sub
End Class