im new in vb and i just create a simple calculation

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

please help me

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 Years
Discussion Span
Last Post by Reverend Jim
dim totprice as decimal
 totprice= Val(txtprice.Text) * Val(txtquantity.Text)

You should be using a try/catch block like this

Dim totprice As Decimal

    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)
    MsgBox("Not a number")
End If

But Try/Catch is probably better.

Votes + Comments
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
            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 ,



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


Please see http://www.a1vbcode.com/vbtip-57.asp

Many programmers use VB's Val() function to convert user inputted strings into numbers. This useful function returns zero (0) for strings that are meaningless as numeric input. Unfortunately, Val() has a bug in its routines. Notably, Val("6%") returns 6, Val("6.%") returns 6, Val("6.0%") returns 6, but Val("6.1%") generates a Type Mismatch error! Hence, for a solid program, no cautious VB programmer can use Val() as-is for generic inputs.

Microsoft makes no mention of Val being deprecated but if you are relying on it to always return a value (even 0) no matter what string you throw at it you should be aware of the above bug. There may be other instances where it could throw an error.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.