problems with listbox

novice:)

Member
Joined
Apr 23, 2010
Messages
5
Programming Experience
Beginner
basically i have buttons which i have given them numbers which appear in the listbox when the button is clicked.
i need to add all the numbers in the list box together and send the total to the text box ive been trying and looking on forums for hours but cant find out how to do it.
any suggestions would be greatly appreciated :D
 
VB.NET:
Dim sum As Integer
For Each number As Integer In ListBox1.Items
    sum += number
Next
 
ListBox1.Items.Add("Cheese + Tomato")
ListBox2.Items.Add("£3.50")
this is what i have done for all of the buttons i have given them a name to come in listbox1
and its price to go into listbox2

i still cant get it to add the items in listbox 2 together and send a total to a text box
 
You can't add strings. You need to add numbers. When you place the pound sign in front of a number, that makes it a string. Remove the pound sign and the quotation marks.

Expanding on JohnH's code:

VB.NET:
	Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
		Dim sum As Double
		ListBox1.Items.Add(3.5)
		ListBox1.Items.Add(4.25)
		ListBox1.Items.Add(2.75)

		For Each number As Double In ListBox1.Items
			sum += number
		Next number
		MessageBox.Show("Sum is " & sum)
	End Sub
 
thanx im almost there just one more problem is its not adding up correctly.
for example i press 2 buttons one worth £3.50 and the other worth £0.50 ... the sum in the message box comes up with a total of £7
which obviously isnt correct
or if i click £3.50 twice it comes up in message box total is £10.50

Public Class Form1
Dim sum As Double

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

ListBox1.Items.Add("Cheese + Tomato")
ListBox2.Items.Add(3.5)
For Each number As Double In ListBox2.Items
sum += number
Next number
MessageBox.Show("sum is " & sum)

End Sub

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
ListBox1.Items.Add("Ham + Pineapple")
ListBox2.Items.Add(4.2)
For Each number As Double In ListBox2.Items
sum += number
Next number
MessageBox.Show("sum is " & sum)
 
This will format the number with 2 places after the decimal point:

VB.NET:
MessageBox.Show("sum is " & sum.ToString("n")


or to format as currency (I don't know how this works with the British pound):

VB.NET:
MessageBox.Show("sum is " & sum.ToString("c")
 
Back
Top