Variable from class is not adding new user input - vb.net

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.

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

Related

Vb When setting price to display in a text box it doesn't display the correct value

I am making a pizza ordering system and I have set the value of price to 0 so that I can add other values onto it later. So when I try to have it display the price as the user selects their items in a text box for some reason is isn't displaying the correct price
Public Class Form1
Public price As Double
Public Psmall As Double = 4.0
Public Pmedium As Double = 7.0
Public Plarge As Double = 9.0
Public Pcrusts As Double = 2.0
Public Pside As Double = 2.5
Public Pdesert As Double = 2.5
Public Pdrinks As Double = 1.0
Public Pizzas As Double = 4.0
Private Sub Psize_SelectedIndexChanged(sender As Object, e As EventArgs) Handles Psize.SelectedIndexChanged
For Each Item As Object In Psize.SelectedItem
orders.AppendText(Item.ToString)
If Psize.SelectedIndex = 0 Then
price += 4
ElseIf Psize.SelectedIndex = 1 Then
price += 7 * 1
ElseIf Psize.SelectedIndex = 2 Then
price += 9 * 1
End If
TextBox1.Text = String.Format("{0:C}", price)
Next
End Sub
Private Sub Pcrust_SelectedIndexChanged(sender As Object, e As EventArgs) Handles Pcrust.SelectedIndexChanged
For Each Item As Object In Pcrust.SelectedItem
orders.AppendText(Item.ToString)
price += Pcrusts
Next
End Sub
Private Sub Pizza_SelectedIndexChanged(sender As Object, e As EventArgs) Handles Pizza.SelectedIndexChanged
For Each Item As Object In Pizza.SelectedItem
orders.AppendText(Item.ToString)
price += Pizzas
Next
End Sub
Private Sub Oside_SelectedIndexChanged(sender As Object, e As EventArgs) Handles Oside.SelectedIndexChanged
For Each Item As Object In Oside.SelectedItem
orders.AppendText(Item.ToString)
price += Pside
Next
End Sub
Private Sub Odesert_SelectedIndexChanged(sender As Object, e As EventArgs) Handles Odesert.SelectedIndexChanged
For Each Item As Object In Odesert.SelectedItem
orders.AppendText(Item.ToString)
price += Pdesert
Next
End Sub
Private Sub Pdrink_SelectedIndexChanged(sender As Object, e As EventArgs) Handles Pdrink.SelectedIndexChanged
For Each Item As Object In Pdrink.SelectedItem
orders.AppendText(Item.ToString)
price += Pdrinks
Next
End Sub
Private Sub orders_TextChanged(sender As Object, e As EventArgs) Handles orders.TextChanged
End Sub
Private Sub tcost_TextChanged(sender As Object, e As EventArgs)
End Sub
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
End Sub
End Class
Above is the code, I have tried using just raw numbers instead of the variable I had already declared and neither has worked
Here is a link to how the code is displaying the price in the form when executed
http://prntscr.com/abmj0a
i think the problem is that you increase the price every time the user select something in the combobox.
So if the user first selects a small pizza, but then changes this to medium pizza, you would set:
prize+=4 'Now the price is at 4
prize+=7 'Now the price is at 11 (4 before and now +7)
So in the end the price would be at 11.
My solution would be:
Declare a price variable for each combobox, for example price_size, price_drink, etc..
Now when the user changes the selection of the size Combobox you just say price_size = 4
And when he changes the drink combobox you say price_drink = 1
And in the end you declare a result_price = price_size + price_drink + ...
Remove every For Each loop in your code. They're completely unnecessary and are most likely what's causing your problems.
You are trying to loop through something that technically doesn't exist.
For Each Item As Object In Psize.SelectedItem
'SelectedItem is just one single item. There's nothing to loop through!
You should also give your price variable an initial value to avoid null reference exceptions.
Public price As Double = 0.0
And lastly, do as julien-100000 said and declare a separate variable holding the price selection for each ComboBox/ListBox.

VB textbox.enter gives null value (accumulator)

Have I simple VB program which accumulating via TextBox.Enter fails. Goal is: how fix TextBox.Enter? I do not get MsgBox, indicating that action tree has not been followed.
Option Explicit On
Public Class MainForm
Public decexpenses, decincome As Decimal
Public dectotalexpenses As Decimal = 0
Public dectotalincome As Decimal = 0
Private Sub MainForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load
MsgBox("Use Enter key to enter values.")
End Sub
Private Sub expensesTextBox_Enter(sender As Object, e As EventArgs) Handles expensesTextBox.Enter
Do Until expensesTextBox.Text = String.Empty
Dim expenses = expensesTextBox.Text
MsgBox(expenses) ' i dont get a msgbox for this indicating this value is null
Do Until IsNumeric(expenses)
MsgBox("Please enter numeric value for expenses.")
Loop
decexpenses = CDec(expenses)
dectotalexpenses = decexpenses + dectotalexpenses
Loop
End Sub
Private Sub incomeTextBox_Enter(sender As Object, e As EventArgs) Handles incomeTextBox.Enter
Do Until incomeTextBox.Text = String.Empty
Dim income = incomeTextBox.Text
Do Until IsNumeric(income)
MsgBox("Please enter numeric value for income.")
Loop
decincome = CDec(income)
dectotalincome = decincome + dectotalexpenses
Loop
End Sub
End Class
Couldn't you just right a method that does the below? It appears that all your looking is to check to make sure it is an integer that was entered into the textbox and if it is calculate it, otherwise display a messagebox to tell the user to enter a number.
Private Sub expensesTextBox_Enter(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles expensesTextBox.KeyPress
Dim dectotalexpenses As Decimal = 0
Dim dectotalincome As Decimal = 0
Dim income As String = expensesTextBox.Text
If Keys.E + Keys.Enter Then
If IsNumeric(income) = True Then
dectotalincome = income + dectotalexpenses
Else
MessageBox.Show("Please Enter A Number")
End If
End If
End Sub

Visual Basic - Simple Bank Transaction [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I believe everything is working correctly but I cannot get the labels to display the calculated data, don't know where I messed up here. Any help would be very much appreciated.
Imports System.IO
Public Class Form1
Dim decMakeWithdrawal As Decimal
Dim decBalace As Decimal
Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click
'Close the form
Me.Close()
End Sub
Private Sub btnDeposit_Click(sender As Object, e As EventArgs) Handles btnDeposit.Click
Dim decMakeDeposit As Decimal
'Add Deposit
decMakeDeposit = CDec(InputBox("Please enter deposit if you have any"))
End Sub
Public Sub btnWithdraw_Click(sender As Object, e As EventArgs) Handles btnWithdraw.Click
Dim decBalance As Decimal
decMakeWithdrawal = CDec(InputBox("Please enter an amount to withdraw"))
If decBalance <= 0 Then
MessageBox.Show("Insufficient funds")
End If
End Sub
Private Sub MainForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim decIntRate As Decimal
decIntRate = CDec(InputBox("Please enter the interest rate:"))
End Sub
Private Function decintTrans() As Object
Throw New NotImplementedException
End Function
Private Sub btnCalculate_Click(sender As Object, e As EventArgs) Handles btnCalculate.Click
Dim decInterTrans As Decimal
Dim decInterest As Decimal
decInterest = CDec(decintTrans())
decInterTrans += 1D
End Sub
End Class
Public Class Transaction
'Create member variables for properties
Public decBalance As Decimal
Private decIntRate As Decimal
Private decInterest As Decimal
Private intTrans As Integer
Private decMakeWithdrawal As Decimal
Private decMakeDeposit As Decimal
Private decInterestEarned As Decimal
'Create property procedures
Public Property Balance As Decimal
Get
Return decBalance
End Get
Set(value As Decimal)
decBalance = value
End Set
End Property
Public Property IntRate As Double
Get
Return decIntRate
End Get
Set(value As Double)
decIntRate = CDec(value)
End Set
End Property
Public Property InterestTotal As Double
Get
Return decInterest
End Get
Set(value As Double)
decInterest = CDec(value)
End Set
End Property
'calculate the amount of interest for the current period
'stores this value in the Interest property, and adds it to the Balance property
Public Sub addInterest(ByVal addInterest As Integer)
decInterestEarned = decBalance * (decIntRate / 12)
End Sub
'add deposit
Public Sub addDeposit(ByVal addDeposit As Decimal)
decMakeDeposit += addDeposit
End Sub
'withdraw
Public Sub subtractWithdrawl(ByVal subtractWithdrawal As Double)
If decMakeWithdrawal >= subtractWith() Then
decMakeWithdrawal = CDec(decMakeWithdrawal - subtractWith())
Else
MessageBox.Show("No sufficient balance")
End If
End Sub
Private Function subtractWith() As Double
Throw New NotImplementedException
End Function
End Class
I feel your code is being complicated by stuff you have added that you are not using at present.
So to simply things, I've cut the extra stuff out and corrected any errors I could see. A lot of tweaking is still needed and like member blackwood states you should validate the values input by the user before processing the data.
Yet still, simply to start you off and set you on the right path, try the code below and don't forget to compare it to your original so you can see where you were going wrong.
Good luck
Option Explicit
Imports System.IO
Public Class Form1
Dim MyTransactor as Transaction
Private Sub MainForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim decIntRate As Decimal
MyTransactor = New Transaction()
decIntRate = CDec(InputBox("Please enter the interest rate:"))
MyTransactor.IntRate = decintRate
End Sub
Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click
'Close the form
Me.Close()
End Sub
Private Sub btnDeposit_Click(sender As Object, e As EventArgs) Handles btnDeposit.Click
Dim decMakeDeposit As Decimal
decMakeDeposit = CDec(InputBox("Please enter deposit if you have any"))
MyTransactor.addDeposit = decMakeDeposit
End Sub
Public Sub btnWithdraw_Click(sender As Object, e As EventArgs) Handles btnWithdraw.Click
decMakeWithdrawal = CDec(InputBox("Please enter an amount to withdraw"))
MyTransactor.subtractWithdrawl = decMakeWithdrawal
End Sub
Private Sub btnCalculate_Click(sender As Object, e As EventArgs) Handles btnCalculate.Click
MyTransactorAddInterest
MessageBox.Show(MyTransactor.InterestEarned & "Interest add to balance. Total balance now is " & MyTranasactor.Balance)
End Sub
End Class
Public Class Transaction
'Create member variables for properties
Public decBalance As Decimal
Private decIntRate As Decimal
Private decInterestEarned As Decimal
'Create property procedures
Public Property Balance As Decimal
Get
Return decBalance
End Get
Set(value As Decimal)
decBalance = value
End Set
End Property
Public Property IntRate As Double
Get
Return decIntRate
End Get
Set(value As Double)
decIntRate = CDec(value)
End Set
End Property
Public Property InterestEarned As Double
Get
Return decInterestEarned
End Get
Set(value As Double)
decInterestEarned = CDec(value)
End Set
End Property
'calculate the amount of interest for the current period
'stores this value in the Interest property, and adds it to the Balance property
Public Sub AddInterest()
decInterestEarned = decBalance * (decIntRate / 12)
decBalance =+ decInterestEarned
End Sub
'add deposit
Public Sub addDeposit(ByVal DepositValue As Decimal)
decBalance=+ DepositValue
End Sub
'withdraw
Public Sub subtractWithdrawl(ByVal WithdrawalValue As Double)
If decBalance >= WithdrawalValue Then
decBalance =- WithdrawalValue
Else
MessageBox.Show("No sufficient balance")
End If
End Sub
End Class

Cannot get derived class to perfom function

I am working on an assignment where I have to create a base class named Bonus. The class should contain two Public properties: a String property named SalesId and a Double property named Sales. I also have to include a default constructor and a parameterized constructor in the class. Also include a GetBonus method (function) that calculates a salesperson’s bonus using the following formula:
sales* .05
Then create a derived class named PremiumBonus. The derived class’s GetBonu method should calculate the commission as follows:
sales * .05 + (sales – 2500) * .01.
Be sure to include a default constructor and a parameterized constructor in the derived class.
This is what I have so far but its only calculating the Bonus not the PremiumBonus when necessary.
Payroll.vb
Option Explicit On
Option Strict On
Option Infer Off
' base class
Public Class Bonus
'declare properties
Public Property SalesId As String
Public Property Sales As Double
'default constructor
Public Sub New()
_Sales = 0
_SalesId = String.Empty
End Sub
'parameterized constructor
Public Sub New(ByVal strId As String, ByVal dblB As Double)
_Sales = dblB
_SalesId = strId
End Sub
'method to calculate the bonus using formula
Public Overridable Function GetBonus() As Double
'returns the sales person's bonus
Return _Sales * 0.05
End Function
End Class
' derived class
Public Class PremiumBonus
Inherits Bonus
Public Sub New()
MyBase.New()
End Sub
Public Sub New(ByVal dblB As Double, ByVal strId As String)
MyBase.New(CStr(dblB), CDbl(strId))
End Sub
Public Overrides Function GetBonus() As Double
Return MyBase.GetBonus + (Sales - 2500) * 0.01
End Function
End Class
Main Form.vb
Option Explicit On
Option Strict On
Option Infer Off
Public Class frmMain
Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click
Me.Close()
End Sub
Private Sub txtSales_Enter(sender As Object, e As EventArgs) Handles txtSales.Enter
txtSales.SelectAll()
End Sub
Private Sub txtSales_KeyPress(sender As Object, e As KeyPressEventArgs) Handles txtSales.KeyPress
If (e.KeyChar < "0" OrElse e.KeyChar > "9") AndAlso e.KeyChar <> "." AndAlso e.KeyChar <> ControlChars.Back Then
e.Handled = True
End If
End Sub
Private Sub txtSales_TextChanged(sender As Object, e As EventArgs) Handles txtSales.TextChanged
lblBonus.Text = String.Empty
End Sub
Private Sub btnCalc_Click(sender As Object, e As EventArgs) Handles btnCalc.Click
' calculates and displays a bonus
' if the sales are over $2500, instantiate a PremiumBonus object
' and then calculate the bonus
' otherwise, instantiate a Bonus object and then calculate the bonus
Dim myBonus As New Bonus
Dim myPremiumBonus As New PremiumBonus
Dim dblSales As Double
If dblSales > 2500 Then
Double.TryParse(txtSales.Text, myPremiumBonus.Sales)
dblSales = myPremiumBonus.GetBonus
Else
Double.TryParse(txtSales.Text, myBonus.Sales)
dblSales = myBonus.GetBonus
End If
' display the bonus
lblBonus.Text = "ID:" & (txtId.Text).PadRight(6) & dblSales.ToString("C2")
End Sub
End Class

Some breakpointed errors and form load event -detailed notes in code

I apologize in advance. I had severe water damage in my apartment today and missed my VB class and professors office hours. She says I can still do this on my own, but it's proving difficult(5:30AM here). I really want to learn it(it is for extra credit), but it she said it will be beneficial for the exam. The example she provided for us isn't any help.
I will provide the attached form and code(which is mostly complete I hope). I've Been struggling all day as I'm new to this. Thanks for ANY help or guidance.
The classes are supposed to be read only.(Balance(need to save value dblBalance), intRate, Interest, intTrans)
**Methods needed** : Calc interest, Withdraw, Deposit
The hint she gave was First, get the interest rate input. Should be in the form_load event
Form should
1) Allows Deposits
2) Allows Withdrawals
3) Calculate interest rate (dblInterestEarned = dblBalance*(dblIntRate/12))
4) Reports current number of transactions at any time - intTrans+=1.
and obviously exit
*Edit I just think I screwed up really bad and made it harder than it should have been. So tired I apologize. Just realized the procedures in the Form.vb Also when form loads input box for interest should pop up first*****
Form[1] http://imgur.com/35Adk2G
Public Class Class1
'Create member variables for properties
Private dblBalance As Double
Private dblIntRate As Double
Private dblInterest As Double
Private intTrans As Integer
Private dblMakeWithdrawal As Double
Private dblMakeDeposit As Double
Private dblInterestEarned As Double
'Create property procedures
Public Property Balance As Double
Get
Return dblBalance
End Get
Set(value As Double)
dblBalance = value
End Set
End Property
Public Property IntRate As Double
Get
Return dblIntRate
End Get
Set(value As Double)
dblIntRate = value
End Set
End Property
Public Property InterestTotal As Double
Get
Return InterestTotal
End Get
Set(value As Double)
InterestTotal = value '''''''*expression recursively calls property interest total
End Set
End Property
''trying to
'''calculate the amount of interest for the current period,
''' stores this value in the Interest property, and adds it to the Balance property.
Public Sub addInterest(ByVal addInterest As Integer)
dblInterestEarned = dblBalance * (dblIntRate / 12)
End Sub
''trying to add deposit
Public Sub addDeposit(ByVal addDeposit As Double)
dblMakeDeposit += addDeposit
End Sub
'''''to withdraw
Public Sub subtractWithdrawl(ByVal subtractWithdrawal As Double)
If dblMakeWithdrawal >= subtractWith() Then
dblMakeWithdrawal -= subtractWith()
Else
MessageBox.Show("No sufficient balance")
End If
End Sub
Private Function subtractWith() As Double
Throw New NotImplementedException
End Function
End Class
Imports System.IO
Public Class Form1
Dim dblMakeWithdrawal As Double
Private Sub btnDeposit_Click(sender As Object, e As EventArgs) Handles btnDeposit.Click
Dim dblMakeDeposit As Double
'''''how to capture inputs from the form load??
'Add Deposit
dblMakeDeposit = CDbl(InputBox("Please enter deposit if you have any"))
End Sub
Private Sub btnWithdraw_Click(sender As Object, e As EventArgs) Handles btnWithdraw.Click
Dim dblBalance As Integer
dblMakeWithdrawal = CDbl(InputBox("Please enter an amount to withdraw")
If dblBalance <= 0 Then
MessageBox.Show("Insufficient funs")
End If
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
'''This is where to put the input box when the form loads? so the read only 3D display boxes update on form?
End Sub
Private Sub GetData(objAccount As Account)
Throw New NotImplementedException
End Sub
End Class
Private Sub btnCalc_Click(sender As Object, e As EventArgs) Handles btnCalc.Click
End Sub
Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click
Me.Close()
End Sub
End Class