vb.net 从字符串 "" 到类型 'Integer' 的转换对每个语句都无效
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28112836/
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
Conversion from string "" to type 'Integer' is not valid on a for each statement
提问by Chrismas007
As the title says, I'm getting an error from my code below, which basically selects multiple inputs on a ListView, and puts it inside a database. Here's the code:
正如标题所说,我从下面的代码中收到一个错误,它基本上选择了 a 上的多个输入ListView,并将其放入数据库中。这是代码:
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
For Each item As ListViewItem In ListView1.SelectedItems
Dim StudentID = Integer.Parse(item.SubItems(0).Text)
Dim FirstName = item.SubItems(1).Text
Dim LastName = item.SubItems(2).Text
DBConn()
SQLSTR = "INSERT INTO '" & TextBox4.Text & "' (StudentID, FirstName, LastName) VALUES ('" & StudentID & "', '" & FirstName & "', '" & LastName & "') "
alterDB()
MsgBox("Students succesfully added", msgboxtitle)
Next
MsgBox("Students added!", , msgboxtitle)
End Sub
The exact error is:
确切的错误是:
An unhandled exception of type 'System.InvalidCastException' occurred in Microsoft.VisualBasic.dll
Additional information: Conversion from string "" to type 'Integer' is not valid.
Microsoft.VisualBasic.dll 中发生类型为“System.InvalidCastException”的未处理异常
附加信息:从字符串 "" 到类型 'Integer' 的转换无效。
回答by Chrismas007
You can use CInt()to convert to Integer. MSDN Reference
您可以使用CInt()转换为整数。MSDN 参考
I'd recommend Dim variable As Typebefore you define the variable though.
不过,我建议Dim variable As Type您在定义变量之前。
Dim item As ListViewItem
Dim StudentID as Integer
Dim FirstName as String
Dim LastName as String
For Each item In ListView1.SelectedItems
StudentID = CInt(item.SubItems(0).Text)
FirstName = item.SubItems(1).Text
LastName = item.SubItems(2).Text

