从字符串“”到类型 'Integer' 的转换在 for each 语句上无效
Conversion from string "" to type 'Integer' is not valid on a for each statement
正如标题所说,我从下面的代码中得到一个错误,它基本上选择 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
准确的错误是:
An unhandled exception of type 'System.InvalidCastException' occurred in Microsoft.VisualBasic.dll
Additional information: Conversion from string "" to type 'Integer' is not valid.
您可以使用CInt()
转换为整数。 MSDN Reference
我建议在定义变量之前 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
正如标题所说,我从下面的代码中得到一个错误,它基本上选择 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
准确的错误是:
An unhandled exception of type 'System.InvalidCastException' occurred in Microsoft.VisualBasic.dll
Additional information: Conversion from string "" to type 'Integer' is not valid.
您可以使用CInt()
转换为整数。 MSDN Reference
我建议在定义变量之前 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