maths function!!!!!!!!

I am new to vb, as you will see below.

I am constructing a simple form which requires some basic maths, whem I try to multiply, the compliers states "C:\Documents and Settings\Jones\My Documents\Visual Studio Projects\VB EXAMPLES\stock2\frmorder.vb(168): Operator '*' is not defined for types 'System.Windows.Forms.TextBox' and 'System.Windows.Forms.TextBox'."

What do I need to set to get the cmdcalc_click function to work. It will not handle the multiplication char?

PrivateSub cmdcalc_Click(ByVal senderAs System.Object,ByVal eAs System.EventArgs)Handles cmdcalc.Click

txttotalprice = txtprice * txtqty

EndSub

Cheers, Jason

[1248 byte] By [jasonjones] at [2007-12-16]
# 1
You first need to get the string that the user entered into the textbox. And because you can do math with text, only numbers, you have to convert it to a number:



Dim Price As Double = CDbl(txtPrice.Text)
Dim Quantity As Integer = CInt(txtQty.Text)
Dim Result As Double = Price * Quantity
txtTotalPrice.Text = Result.ToString()

DanielRieck at 2007-9-9 > top of Msdn Tech,Visual Basic,Visual Basic General...
# 2

Observation 1:

You are trying to multiply two textboxes with each other, not the text in the textboxes. Try this instead:



txttotalprice.Text = txtprice.Text * txtqty.Text

Observation 2:
Personally, I don't like to allow the compiler to make all of these magic conversions - I'm an "Option Strict On" type of guy. While it can be convenient to let the compiler determine that it can actually convert the value of the text in the textboxes into numerical values, multiply those values, and to top it all, convert the resulting numerical values back to a string, I have found it to be a source of hard-to-discover bugs. So you would have to explicitly tell the compiler what types you want to convert the strings to:

(at the top of the file)


Option Strict On





TextBox1.Text = (CDbl(TextBox1.Text) * CDbl(TextBox1.Text)).ToString()

Observation 3:
There is no error handling here. What if the user was nasty enough to put something that wasn't a numerical value in the textbox? Or a value that was too big? (Yeah, I know, this is somewhat beyond the scope of the original question)

Best regards,
Johan Stenberg

JohanStenberg at 2007-9-9 > top of Msdn Tech,Visual Basic,Visual Basic General...
# 3

Daniel,

Thanks for your help.

I have tried this solution but I get a microsoft development message saying "An unhandled exception of type 'System.InvalidCastException' occurred in microsoft.visualbasic.dll

Additional information: Cast from string "" to type 'Integer' is not valid.

Any ideas?

Thanks, Jason

jasonjones at 2007-9-9 > top of Msdn Tech,Visual Basic,Visual Basic General...
# 4
Johan,

Thanks, it worked fine.

I appreciate your observations, I come from an industrial background (robotics and plc control) so I am just finding my feet in .net

Cheers, Jason

jasonjones at 2007-9-9 > top of Msdn Tech,Visual Basic,Visual Basic General...