为什么这段代码会引发FormatException? [英] Why is this code throwing a FormatException?

查看:92
本文介绍了为什么这段代码会引发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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆