为什么这段代码会引发FormatException? [英] Why is this code throwing a FormatException?
问题描述
我写了以下代码:
Dim E_ID As Integer
E_ID = Convert.ToInt16(Request.QueryString("ID"))
但是当它执行时,我总是得到一个FormatException
:
But when it executes, I always get a FormatException
:
错误:输入字符串的格式不正确.
error: Input string was not in a correct format.
这可能是什么原因造成的?
What could be causing 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
推荐答案
由于Request.QueryString("ID")
函数调用返回的任何值都不能转换为Int16
类型.根据 Convert.ToInt16
方法的文档,
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:
值不包含可选的符号,后跟数字序列(0到9).
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)
这篇关于为什么这段代码会引发FormatException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!