Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Infinity error 1

Status
Not open for further replies.

officemanager2

Technical User
Oct 11, 2007
116
CA
Currently I'm in the early stages of using Visual Studio after working in Access. This code is an exercise to make me better at writing code.

When I run this I get an Invalid Cast Exception

Following the error messages I see is says conversions from string to integer is not valid

Unfortunately I cannot see where the code is trying to make this conversion?

Code:
 Private Sub Complete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Complete.Click
        Dim CurrentAmount As Integer
        Dim Split1 As Integer
        Dim Split2 As Integer
        Dim RemainOrg As Integer
        Dim Total As Integer

        CurrentAmount = IntCurAmt.Text
        Split1 = IntSplit1.Text
        Split2 = IntSplit2.Text
        RemainOrg = IntRemainOrg.Text
        Total = IntTotal.Text

        Total = Split1 + Split2 + RemainOrg
        IntTotal.Text = Total

        If Total <> CurrentAmount Then
            MsgBox("The Total is Incorrect")
        Else
            MsgBox("The Total is Correct")
        End If

The error seems to be based around

Code:
Total = IntTotal.Text

but at this point I cannot figure out what is going wrong. If I would guess I would say that I need a method after IntTotal whereas I believe I currently have it set as a property.

thanks
 
The heart of the issue it seems to me is the code getting integer and string variables/objects mixed.
I suggest that read about casting types ( e.g. CINT, Cstring etc and .String property )
Shown bellow are some possible solutions, but be warned this code was typed freehand and no testing was done!
I am assuming that there are objects (most likely textboxes on a form ) named IntCurAmt, IntSplit1 etc.

Code:
Private Sub Complete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Complete.Click

	Dim CurrentAmount As Integer = cint(IntCurAmt.Text)
	Dim Split1 As Integer  = cint( IntSplit1.Text  )      
	Dim Split2 As Integer  = cint( IntSplit2.Text )      
	Dim RemainOrg As Integer   = cint( IntRemainOrg.Text )      
	Dim Total As Integer   = cint( IntTotal.Text ) + Split1 + Split2 + RemainOrg    
         
	IntTotal.Text = string( Total )
	
	If Total <> CurrentAmount Then            
		MsgBox("The Total is Incorrect")        
	Else            
		MsgBox("The Total is Correct")        
	End If
	
	... More Code

-Another solution

Code:
Private Sub Complete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Complete.Click

	If cint(IntCurAmt.Text) <> ( cint( IntTotal.Text ) + cint( IntSplit1.Text  ) + cint( IntSplit2.Text ) + cint( IntRemainOrg.Text ) )  Then            
		MsgBox("The Total is Incorrect")        
	Else            
		MsgBox("The Total is Correct")        
	End If
	
	... More Code

-Another solution
Code:
Private Sub Complete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Complete.Click
	
    MsgBox("The Total is " & If(cint(IntCurAmt.Text) <> ( cint( IntTotal.Text ) + cint( IntSplit1.Text  ) + cint( IntSplit2.Text ) + cint( IntRemainOrg.Text ) ) , _
  	"Incorrect", "Correct"))
	
	... More Code


Lion Crest Software Services
Anthony L. Testi
President
 
This code is an exercise to make me better at writing code. "
Great! Keep it up.

BTW The "Invalid Cast Exception" is because (I think that is) the code is trying to put am integer into a string (or vice-versa)

Lion Crest Software Services
Anthony L. Testi
President
 

If any of your text boxes (IntCurAmt, IntSplit1, IntSplit2, IntRemainOrg) are empty, you will get this error.

You may also try:
Code:
        CurrentAmount = [blue]Val([/blue]IntCurAmt.Text[blue])[/blue]
        Split1 = [blue]Val([/blue]IntSplit1.Text[blue])[/blue]
        Split2 = [blue]Val([/blue]IntSplit2.Text[blue])[/blue]
        RemainOrg = [blue]Val([/blue]IntRemainOrg.Text[blue])[/blue]
        Total = [blue]Val([/blue]IntTotal.Text[blue])[/blue]

BTW, it it would be me, I would change the way of naming the controls/variables:

Code:
        intCurrentAmount = Val(txtCurAmt.Text)
        intSplit1 = Val(txtSplit1.Text)
        intSplit2 = Val(txtSplit2.Text)
        intRemainOrg = Val(txtRemainOrg.Text)
        intTotal = Val(txtTotal.Text)
This way I know anywhere in my code that anything with the prefix of [tt]int[/tt] is an Integer, anything with [tt]txt[/tt] is a text box, str - String, cbo - combo box, etc. But ... that's me.

Have fun.

---- Andy
 
Thanks for the feedback from both of you. Adding the 'val' is what was missing, so I'll push forward on this from here.

Mr Data Guy: Do you feel that 'cint' works better than 'val'. I'd never come across cint until you posted and I understand that it is tied into turning an integer into a value, but I've also come across postings that talk about cint being used to always round up. Not sure which one is considered correct, of if both answers are correct.

Andrzejek: When you put the following

IntCurrentAmount = Val(IntCurAmt.Text)

I must then declare the variable as follows:

Dim IntCurrentAmount As Integer

I initially added the Int, but then I kept getting error messages that I had not declared the variable. Currently I have the variable declared as

Dim CurrentAmount As Integer


Well I'll see what happens from here. The next goal is to pass a variable ... at least I think that is how one is supposed to say it.

thanks again
 
To declare or initialize the variable, all that is needed is:
IntCurrentAmount = 0. The actual int in the name doesn't mean anything, its just a name to reference that particular variable.

If at first you don't succeed, then sky diving wasn't meant for you!
 
Mr Data Guy: Do you feel that 'cint' works better than 'val'. I'd never come across cint until you posted and I understand that it is tied into turning an integer into a value, but I've also come across postings that talk about cint being used to always round up. Not sure which one is considered correct, of if both answers are correct. "

OK first of all I am not a VB.Net Expert (Been programming for 25+ years and learning every day.) That said I have never used (nor heard of) a vb.Net VAL() function. So I figured, OK chance to learn a new function, and did some research.

Found this online article:
"To Val or not to Val, That is the Question"

Bottom line (for me) would be not to use the VAL() per these comments from article:

-"...old school VB6 functions, amongst which was VAL..."
(Note I want to use .net not the older VB6 coding)

-"So, while you think Val is returning an INT, it isn't"

-"Option Strict turned OFF (which should be a crime), you'd never no (Know)"
(Note I agree that programming with option strict OFF is a programming 'crime'. I get very frustrated when I cut and paste example code from some source and find sometimes dozens of issues with the code, because all of my projects have set strict ON. To me that is one sign or lack there of, of a professional developer. OK Pardon me as I get off of my Soapbox.)

Also the CINT follows the pattern of all the Cast Functions: Cint, CString, cBool etc etc.

Lion Crest Software Services
Anthony L. Testi
President
 
The next goal is to pass a variable ... at least I think that is how one is supposed to say it."

Well if you want to be correct the word to use is “Argument” not “variable”. However 99% of the time I use the term variable myself.

BTW for what it is worth I almost always pass by value not by reference. Reason I do not want the chance the method being called changing my variable/argument.
FYI: Here is some code that I just wrote. Note that I Prefix my parameters with a lower case ‘p’. That is my style (you have my permission to use it, <grin>). It is NOT a standard programming practice in the VB.NET (Wish it was thou) I use it to help me see that a variable is a parameter of the method (vs a class property or something else.)
Code:
    Public ReadOnly Property Time_Total_Revenue_Decimal_Hours() As Double
        Get
            Return _
              Me.Calc_Delta_Time(Me._Program.TimeHHMM_to_Minutes(Me.Time_Rev_Start),_
              Me._Program.TimeHHMM_to_Minutes(Me.Time_Rev_End))
        End Get
    End Property

    Private Function Calc_Delta_Time(ByVal pTime_Start As Integer, _
                                     ByVal pTime_End As Integer) As Double
        If pTime_Start = 0 OrElse pTime_End = 0 Then
            Return 0
        Else
            Return Math.Round((pTime_End - pTime_Start) / 60, 2)
        End If

    End Function



Lion Crest Software Services
Anthony L. Testi
President
 
I prefer TryParse to validate and convert text data as it won't throw any exceptions. I'd also advise against prefixing TextBoxes with "Int"; that's going to cause confusion for the person (including yourself) maintaining the code in the future. Here's my over-engineered take on your original code.
Code:
    Private Sub btnComplete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnComplete.Click
        Dim currentAmount As Integer
        Dim split1 As Integer
        Dim split2 As Integer
        Dim remainOrg As Integer

        Dim okCurrentAmount As Boolean = Integer.TryParse(txtCurrentAmount.Text, currentAmount)
        Dim okSplit1 As Boolean = Integer.TryParse(txtSplit1.Text, split1)
        Dim okSplit2 As Boolean = Integer.TryParse(txtSplit2.Text, split2)
        Dim okRemainOrg As Boolean = Integer.TryParse(txtRemainOrg.Text, remainOrg)

        If (Not okCurrentAmount) Then
            txtTotal.Text = "Unable to parse Current Amount"
        ElseIf (Not okSplit1) Then
            txtTotal.Text = "Unable to parse Split1"
        ElseIf (Not okSplit2) Then
            txtTotal.Text = "Unable to parse Split2"
        ElseIf (Not okRemainOrg) Then
            txtTotal.Text = "Unable to parse Remain Org"
        ElseIf (currentamount <> (split1 + split2 + remainOrg)) Then
            txtTotal.Text = "Incorrect Total"
        Else
            txtTotal.Text = split1 + split2 + remainOrg
        End If

    End Sub
 

I admit, Val is the ‘left over’ logic from VB 6

But all of this comes down to validating user’s input into some text boxes. So it would make sense to me to restrict user to input only integers into those text boxes and do the validation at the Key_Press event of the text boxes.


Have fun.

---- Andy
 
Well this seems like it has turned into a productive thread, but I must admit the discussion is getting beyond what I currently understand. I am curious if there is any input for the following two issues:

Once an amount is put into the split field I would like to open up a form (already built) that would allow the split to be given a unique number (not a primary key though) and have other information brought up that would be tied into the initial current amount. In access I would use ondirty to open the from but I can't figure out how to get this done in VB.net (I've been trying for a few hours now - yes I'm very new to this).

The other issue ties into an error after the split. It is fine if the box comes up to inform that there is an error, but if the end user can simply click 'ok' and still carry on with the split which will cause problems down the line when numbers don't balance. Once again I've seen something like this in Access but can't figure out what to do here.

I'm not sure if the protocol on this board is to start a new thread for these issues or if I can carry on from this one? If any mods would prefer a new thread I will of course accommodate.

thanks
 

To answer one question - you may want to set focus to the text box with wrong entry and prevent from going on with the wrong value (BLUE code):
Code:
        If (Not okCurrentAmount) Then
            txtTotal.Text = "Unable to parse Current Amount"
            [blue]txtCurrentAmount.Focus()[/blue]
        ElseIf (Not okSplit1) Then
            txtTotal.Text = "Unable to parse Split1"
            [blue]txtSplit1.Focus()[/blue]
        ElseIf (Not okSplit2) Then
            txtTotal.Text = "Unable to parse Split2"
        ElseIf (Not okRemainOrg) Then
            txtTotal.Text = "Unable to parse Remain Org"
        ElseIf (currentamount <> (split1 + split2 + remainOrg)) Then
            txtTotal.Text = "Incorrect Total"
        Else
            txtTotal.Text = split1 + split2 + remainOrg
        End If

For new issues not related to the original I would start a new thread

Have fun.

---- Andy
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top