-1

I understand this might be considered a duplicate of this: Parse v. TryParse

But, could anybody tell me why this code threw an exception when Tryparse is not supposed to throw any exceptions at all?

If Int32.TryParse(txtOrdLine.Text.Trim, txtOrdLine.Text) = False Then

The value entered in txtOrdLine was "1-4".

The exception was that it could not convert string "1-4" to type Integer. This is on a code behind for a ASP.Net 4.5 site if that makes a difference.

Any information would be appreciated.

Thanks.

Community
  • 1
  • 1
A.Stair
  • 11
  • 1
  • 4
  • 2
    Your second parameter has to be an integer type variable. – LarsTech Aug 21 '15 at 20:05
  • It is being converted automatically when it is a valid number so that is not the case. Besides, the error is from string to integer, not the other way around. – A.Stair Aug 21 '15 at 20:07
  • 3
    Set [Option Strict On](https://msdn.microsoft.com/en-us/library/zcd4xwzs.aspx) to point out problems like that in the code. – Andrew Morton Aug 21 '15 at 20:09
  • Hmm, no. The [Int.TryParse](https://msdn.microsoft.com/en-us/library/f02979c7(v=vs.110).aspx) function wants that second parameter to be an integer. – LarsTech Aug 21 '15 at 20:10
  • Agree with Andrew and Lars. What is this code trying to accomplish? – dbasnett Aug 21 '15 at 22:18

2 Answers2

2

The error is occurring because the automatic conversion the second parameter from String to Int32 is failing.

VB.Net is effectively re-writing your code as:

Dim temp as Int32
temp = Int32.Parse(txtOrdLine.Text) ' Exception here!
Int32.TryParse(txtOrdLine.Text.Trim, temp)
txtOrderLine.Text = temp.ToString()

You'll need to create a temporary Int32 value and pass that into Int32.TryParse()

shf301
  • 31,086
  • 2
  • 52
  • 86
0

If this is just a check then you don't need a variable.

    If Not Int32.TryParse(txtOrdLine.Text.Trim, Nothing) Then
        'here if parse fails
    End If
dbasnett
  • 11,334
  • 2
  • 25
  • 33