从字符串 "" 到类型 'Integer' 的转换无效。- VB.NET

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17419172/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 14:06:36  来源:igfitidea点击:

Conversion from string "" to type 'Integer' is not valid. - VB.NET

vb.netinputbox

提问by nirosha rathnayaka

When I click cancel button of the input box it shows this 'Conversion from string "" to type 'Integer' is not valid.' error in vb.net 2010. My code is,

当我单击输入框的取消按钮时,它显示此“从字符串“”转换为类型“整数”无效。vb.net 2010 中的错误。我的代码是,

Dim lineNo As Integer

lineNo = InputBox("What is the last record number?" & 
vbNewLine & vbNewLine & "Enter line number 0 - 30.", "Enter Line Number", 0)

What's the wrong in here?

这里有什么问题?

Update: Dim lineNo As Integer. I have forgotten to state the declaration here.

更新:Dim lineNo As Integer。我忘记在这里声明声明了。

回答by Carlos Landeras

Declare lineNoas string:

声明lineNo为字符串:

Dim lineNo As String = InputBox("What is the last record number?" &
    vbNewLine & vbNewLine & "Enter line number 0 - 30.", "Enter Line Number", 0)

lineNomust be declared as integer somewhere else in your code. Just pasted my code on visual studio and no complaints.

lineNo必须在代码中的其他地方声明为整数。刚刚在visual studio上粘贴了我的代码,没有任何抱怨。

Even use another string variable if you need lineNo as integer.

如果需要 lineNo 作为整数,甚至可以使用另一个字符串变量。

回答by Alexander

I presume lineNo is declared as Integer? Clicking "Cancel" on the InputBox will return an empty string, and an emptry string cannot be converted to a numeric value. That's what your error says. So you should get the result of the InputBox, which always returns a String, and convert it in a separate step, maybe with Integer.TryParse.

我认为 lineNo 被声明为整数?在 InputBox 上点击“取消”将返回一个空字符串,空字符串不能转换为数值。这就是你的错误所说的。所以你应该得到 InputBox 的结果,它总是返回一个字符串,并在一个单独的步骤中转换它,也许用Integer.TryParse.

回答by matzone

since your inputbox return string so you have to do

因为你的输入框返回字符串所以你必须做

lineNo = val(InputBox("What is the last record number?" & vbNewLine & vbNewLine & "Enter line number 0 - 30.", "Enter Line Number", 0))