|
-
Aug 20th, 2007, 06:12 PM
#1
Thread Starter
Hyperactive Member
Simple Cast not working
I cannot figure out what I am doing wrong. This is a very simple cast:
vb Code:
'sng casting test
Dim varFF As Single = CSng(tbCalcFF.Text) - CSng(tbGoalFF.Text)
If varFF < 0 Then
tbCalcFF.BackColor = Color.Gold
Else
tbCalcFF.BackColor = Color.LightGoldenrodYellow
End If
I am getting this error: Conversion from string "" to type 'Single' is not valid.
-
Aug 20th, 2007, 06:39 PM
#2
Re: Simple Cast not working
Thats because either tbCalcFF.Text or tbGoalFF.Text is equal to "", you cant turn that into a valid single value.
What you should do is use Single.TryParse, its handy whenever you are unsure if the string can be converted or not.
VB Code:
Dim value1 As Single
Dim value2 As Single
If Single.TryParse(tbCalcFF.Text, value1) AndAlso Single.TryParse(tbGoalFF.Text, value2) THen
Dim varFF As Single = value1 - value2
If varFF < 0 Then
tbCalcFF.BackColor = Color.Gold
Else
tbCalcFF.BackColor = Color.LightGoldenrodYellow
End If
Else
MessageBox.Show("Enter valid single values!")
End If
Last edited by Atheist; Aug 20th, 2007 at 06:48 PM.
-
Aug 20th, 2007, 08:10 PM
#3
Re: Simple Cast not working
Another thing you might try, along the same lines, would be to split that one If statement into two, because if the return from either one is false, you could simply put a 0 into that value on the assumption that an empty string is basically 0 (or some other default value if something else makes sense).
Come to think of it, that's kind of obvious, but sometimes we try to make nice neat, tight, code, and sacrifice useability.
My usual boring signature: Nothing
 
-
Aug 20th, 2007, 08:16 PM
#4
Re: Simple Cast not working
 Originally Posted by Shaggy Hiker
Another thing you might try, along the same lines, would be to split that one If statement into two, because if the return from either one is false, you could simply put a 0 into that value on the assumption that an empty string is basically 0 (or some other default value if something else makes sense).
Come to think of it, that's kind of obvious, but sometimes we try to make nice neat, tight, code, and sacrifice useability.
Yeah good thinking. Then I suppose this would work aswell.
VB Code:
Dim value1 As Single
Dim value2 As Single
Single.TryParse(tbCalcFF.Text, value1)
Single.TryParse(tbGoalFF.Text, value2)
Dim varFF As Single = value1 - value2
If varFF < 0 Then
tbCalcFF.BackColor = Color.Gold
Else
tbCalcFF.BackColor = Color.LightGoldenrodYellow
End If
Because value1 and value2 will keep their default values of 0 if TryParse fails. However, I suppose that using an IF statement to check wether the textboxes are empty or not as you mentioned would be more efficient.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|