newbie question - Conversion using CDec from string to type 'Decimal' is not valid

aappiah

New member
Joined
Jan 28, 2010
Messages
2
Programming Experience
Beginner
Hi

Please excuse the newbie question as I started learning VB last week . I wrote the following test code below to add two values entered in two textboxes and display it in another textbox. However I keep getting the exception.

"Conversion from string "" to type 'Decimal' is not valid"

with the code below and I cannot figure out why . I thought converting using 'CDec' resolves this issue ?


Please advise

Cheers Alfred

---
Private Sub sumTotal_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles sumTotal.Click

Dim total As Decimal = CDec(operand1.Text + operand2.Text)
 
Yur are ADDING two STRINGS and the RESULT ist converted to Decimal. Since the result is decimal, the compiler wants to convert the operands to Decimal too.
Dim total As Decimal = CDec(operand1.Text) + CDec(operand2.Text)

Since converting user input is always insecure, you'd better use .TryParse
[vb]
dim d1, d2, result as decimal
if decimal.tryparse(string1, d1) and decimal.tryparse(string2, d2) then result=d1 + d2
[/vb]
 
Muchos Gracias Picoflop

Dim total As Decimal = CDec(operand1.Text) + CDec(operand2.Text) provides the solution and I see where I was making the error .

Cheers Al
 
User input entered as strings in a Textbox is not safe to convert to Decimal, TryParse is the safe conversion for that. Using a NumericUpDown, which is kind of a silly name for a 'NumericTextBox', may be a better solution for that, you can get the input from Value property and it is already Decimal type.
 
Back
Top