CathaysMafia CathaysMafia - 7 days ago 6
Vb.net Question

How do I multiply one text box with another text box and display the result in a List view?

I have one form (frmBuy) where the price (txtPrice) is displayed and user can change the quantity (txtQuantity). once the user presses the cmdAdd button the quantity is displayed on another form (frmBasket) in a ListView (lvwQuantity). I want to know how to multiply the price and the quantity textboxes, then display the result on another form (frmBasket) in a ListView (lvwTotal) when the cmdAdd button is pressed.

This is the code I have for transferring the quantity:

Private Sub cmdAdd_Click(sender As Object, e As EventArgs) Handles cmdAdd.Click
frmBasket.lvwQuantity.Items.Add(txtQuantity.Text)
End Sub

Answer

First, parse the strings to numbers:

Dim price As Decimal
Dim quantity As Integer;
If Not Decimal.TryParse(txtPrice.Text, ByRef price) 
       Or Not Integer.TryParse(txtQuantity.Text, ByRef quantity) Then
    ... 'Cannot parse to numbers, possibly invalid input
Else

Then, you can just multiply them and add them to the list view:

    frmBasket.lvwTotal.Items.Add(price * quantity)
End If

You might also want to consider data binding, which would make this part a lot cleaner. I.e. set up a class representing an entry with price and quantity. This class could have a calculated property for the total amount. Then, you would bind the list views to a list of this class and frmBuy would only need to add items to this list.

Comments