Why is this code throwing a FormatException?

790 views Asked by At

I have written the following code:

 Dim E_ID As Integer
 E_ID = Convert.ToInt16(Request.QueryString("ID"))

But when it executes, I always get a FormatException:

error: Input string was not in a correct format.

What could be causing this?

i am sending value like this.

Protected Sub lnkPrint_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles lnkPrint.Click
        lnkPrint.Attributes.Add("onclick", "return openBadgeReportPage('" + ddEvent.DataValueField + "','" + ddType.DataValueField + "')")
    End Sub
End Class
2

There are 2 answers

0
Cody Gray - on strike On BEST ANSWER

Because whatever value is being returned by the Request.QueryString("ID") function call is not convertible to an Int16 type. According to the documentation for the Convert.ToInt16 method, a FormatException is thrown whenever the:

value does not consist of an optional sign followed by a sequence of digits (0 through 9).

You can see what value is actually being returned by separating your code out into a couple of different lines, and setting a breakpoint. For example:

Dim E_ID As Integer
Dim queryString As String
queryString = Request.QueryString("ID")    ' <-- place breakpoint here
E_ID = Convert.ToInt16(queryString)
2
Raghu On

There are 2 things you need to note here:

1) You are trying to assign an Int16 to an Integer (32 bit by default). This is a valid operation, however there is a chance you could introduce a bug in your application.

2) As Cody mentioned the value returned by Request.QueryString("ID") may not be convertible to an Int16 and hence the error. You can try the following code to verify the value returned by the Request.QueryString("ID") statement in a safer way:

Dim E_ID As Int16
Boolean isInteger = Int16.TryParse(Request.QueryString("ID"), out E_ID)

If isInteger Then
     // you have a valid short int inside the E_ID variable now.