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)

Recommended Answers

All 7 Replies

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.

commented: Good solution... +5

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

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.