Why is this code throwing a FormatException?

試著忘記壹切 提交于 2019-12-12 01:58:29

问题


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

回答1:


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:


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.


来源:https://stackoverflow.com/questions/4850259/why-is-this-code-throwing-a-formatexception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!