为什么这段代码会抛出 FormatException?
我编写了以下代码:
Dim E_ID As Integer
E_ID = Convert.ToInt16(Request.QueryString("ID"))
但是当它执行时,我总是得到一个FormatException
:
错误:输入字符串的格式不正确。
可能是什么原因造成的?
我正在发送这样的值。
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
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
因为
Request.QueryString("ID")
函数调用返回的任何值都不能转换为Int16
类型。根据Convert.ToInt16
方法的文档,FormatException
是每当出现以下情况时抛出:您可以通过将代码分成几行并设置断点来查看实际返回的值。例如:
Because whatever value is being returned by the
Request.QueryString("ID")
function call is not convertible to anInt16
type. According to the documentation for theConvert.ToInt16
method, aFormatException
is thrown whenever the: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:
这里需要注意两件事:
1)您尝试将 Int16 分配给 Integer(默认情况下为 32 位)。这是一个有效的操作,但是您有可能在应用程序中引入错误。
2)正如 Cody 提到的,Request.QueryString("ID") 返回的值可能无法转换为 Int16,因此会出现错误。您可以尝试以下代码以更安全的方式验证 Request.QueryString("ID") 语句返回的值:
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: