im new in vb and i just create a simple calculation

if i click the button for compute it will display the error

``````Dim price As Decimal = txtprice.Text
Dim quantity As Integer = txtquantity.Text
Dim totalprice As Decimal = txttotal.Text
totalprice = quantity * price``````

working code below

``txttotal.Text = Val(txtprice.Text) * Val(txtquantity.Text)``

Edited by ceteris: n/a

5
Contributors
7
Replies
10
Views
5 Years
Discussion Span
Last Post by Reverend Jim
``````dim totprice as decimal
totprice= Val(txtprice.Text) * Val(txtquantity.Text)
txttotal.Text=totprice``````

You should be using a try/catch block like this

``````Dim totprice As Decimal

Try
totprice = CDec(txtPrice.Text)
MsgBox("value is " & totprice.ToString)
Catch ex As System.InvalidCastException
MsgBox("not a number")
End Try``````

If the conversion is not successful the "Catch" portion will be executed. Another way to test without Try/Catch is

``````If IsNumeric(txtPrice.Text) Then
totprice = CDec(txtPrice.Text)
Else
MsgBox("Not a number")
End If``````

But Try/Catch is probably better.

Good solution...

I would try to skip the entire Try/Catch on this issue and check if a numeric value.

``````If IsNumeric(txtPrice.Text) Then
'// do stuff here
Else
MsgBox("Not a number")
End If``````

Just my 2.cents worth.

hello !
try this

``````Dim price As Decimal = val(txtprice.Text)
Dim quantity As Integer = val(txtquantity.Text)
Dim totalprice As Decimal = val(txttotal.Text)
totalprice = val(val(quantity) * val(price))``````

this will work fine ,

Regards

Not to start anything here, though I do believe that "val" is vb6- related and could possibly cause issues in future .Net Frameworks.

no , val does not cause any issue in vb.net as i am continuously using it in about 2.5 years , :)

Regards