首页 > 解决方案 > Variable from class is not adding new user input

问题描述

I am creating an accounting app for my homework. The application needs to have a seperate class that holds the variables for Balance, Interest, Interest Rate, and number of transactions. The balance should change with every withdraw and deposit.

I currently have a public sub in the balance class that adds the deposit to a variable that checks for negative values. In the main for on btnDeposit click I have the label pull the variable from the balance class to display. It shows the value but, next input is not added to the variable it just displays the current deposit.

Public Class Balance

    Public dblBalance As Double
    Public decDeposit As Decimal
    Public decWithdraw As Decimal
    Public dblIntrest As Double
    Public dblIntRate As Double
    Public intTransactions As Integer

    Public Sub New()
        dblBalance = 0
        intTransactions = 0
        decDeposit = 0
        decWithdraw = 0
        dblIntRate = 5
        dblIntrest = 0

    End Sub

    Public Sub MakeDeposit()

        decDeposit = InputBox("Enter the Deposit Amount", "Deposit", "0.00")

        If decDeposit < 0 Then
            MessageBox.Show("Enter a Positive Number")
        ElseIf decDeposit >= 0 Then
            dblBalance += decDeposit
            intTransactions += 1
        End If


    End Sub

Public Class Form1

    Private Sub btnDeposit_Click(sender As Object, e As EventArgs) Handles btnDeposit.Click

        Dim Balance = New Balance()

        Balance.MakeDeposit()

        lblBalance.Text = Balance.dblBalance.ToString("C")
        lblTransactions.Text = Balance.intTransactions

    End Sub

    Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click
        Me.Close()
    End Sub

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        lblBalance.Text = 0.ToString("C")
        lblInterest.Text = 0.ToString("C")
        lblIntRate.Text = 0.ToString("P")
        lblTransactions.Text = 0.ToString("G")

    End Sub
End Class

The variable should be adding the value every time.

标签: vb.netwinforms

解决方案


It looks like your deposit button click event holds the variable that stores the instance of your deposit class. So, every time you click that button, it creates the class, then destroys it once the button click event is done. You will want to change Dim Balance = New Balance() to a class level variable, moving it out of the button click procedure as follows

Public Class Form1
    Dim Balance = New Balance()
    Private Sub btnDeposit_Click(sender As Object, e As EventArgs) Handles btnDeposit.Click
        Balance.MakeDeposit()
        lblBalance.Text = Balance.dblBalance.ToString("C")
        lblTransactions.Text = Balance.intTransactions
    End Sub

推荐阅读