Question Arithmatic operation problem

vb_noob

Member
Joined
Mar 28, 2011
Messages
6
Programming Experience
Beginner
Hi there,

This is probably a simple problem but I really couldn't get it working for the life of me.

I'm trying to calcuate grandtotal value using total;
VB.NET:
Dim productsold As Decimal
Dim productprice As Decimal
Dim totalsales As Decimal
Dim grandtotalsales As Decimal

productsold = (Val(txtNumProd.Text))
productprice = (Val(txtProdPrice.Text))
totalsales = productprice * productsold
grandtotalsales = grandtotalsales + totalsales
lblTotalOutput.Text = "The total sales price is " & FormatCurrency(totalsales)
lblGrandTotalOutput.Text = "Grand Total sales price is " & FormatCurrency(grandtotalsales)

totalsales work just fine. It's the grandtotalsales that won't work.
Is my formula wrong? Or any other problems?

Please let me know. Thank you.

Regards,
vb_noob
 
You only sold one item, so the grand total is the same as the total.

If you're trying to enter more items and add them up with the code in a button click event, then all the variable values will start over again from 0. Local variables go out of scope and are removed from memory once the procedure ends. What you need to do is declare the grand total variable at the class level, before any of the event procedures.

For example:

VB.NET:
Public Class Form1

	Dim grandtotalsales As Decimal

	Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
		Dim productsold As Decimal
		Dim productprice As Decimal
		Dim totalsales As Decimal

		productsold = (Val(txtNumProd.Text))
		productprice = (Val(txtProdPrice.Text))
		totalsales = productprice * productsold
		grandtotalsales = grandtotalsales + totalsales
		lblTotalOutput.Text = "The total sales price is " & FormatCurrency(totalsales)
		lblGrandTotalOutput.Text = "Grand Total sales price is " & FormatCurrency(grandtotalsales)
	End Sub

End Class
 
Given that you haven't told us what your formula is, it's a bit hard to tell. From that code, your grandtotalsales will be the same as your totalsales.
I did, mate. It was grandtotalsales = grandtotalsales + totalsales. Maybe not the best one but this was the the only thing I could think of :)
Thanks for the reply.

You only sold one item, so the grand total is the same as the total.

If you're trying to enter more items and add them up with the code in a button click event, then all the variable values will start over again from 0. Local variables go out of scope and are removed from memory once the procedure ends. What you need to do is declare the grand total variable at the class level, before any of the event procedures.

OMG it works like a charm!!! I can't believe the solution is this simple. I just cut the variable declaration and pasted in form public class and that's it.
Thank you very much, Solitaire. I really appreciate your help. Can't tell you how chuffed I am :D

Cheers and regards,
vb_noob
 
Back
Top