我很难解决此错误
将varchar值转换为Integer
时转换失败
代码似乎运行正常,我在其他代码上使用它,但唯一的区别是我使用的主键,对于这个我用了一个整数,而在其他代码我使用nvarchar
为他们首要的关键。感谢您提前得到任何答案。
这是我的代码:
Private Sub deleteIndv()
Dim result
Dim id As String = Me.DataGridView2.CurrentRow.Cells(0).Value
Using cmd As New SqlClient.SqlCommand
result = MsgBox(" Are You Sure You Want to Delete the Selected Row ? ", MsgBoxStyle.YesNo)
TextBox2.Text = Me.DataGridView2.CurrentRow.Cells(0).Value.ToString
' Try
If result = Windows.Forms.DialogResult.No Then
Exit Sub
Else
If con.State = ConnectionState.Closed Then
con.Open()
End If
cmd.Connection = con
cmd.CommandText = "DELETE FROM IndvReports WHERE Id_indv = " & id
cmd.Parameters.AddWithValue("@id", id)
cmd.ExecuteNonQuery()
Me.DataGridView2.Rows.Remove(Me.DataGridView2.CurrentRow)
MsgBox(" Record Successfully Deleted! ", MsgBoxStyle.Information)
cmd.Parameters.Clear()
End If
'Catch ex As Exception
' MsgBox(" Error Deleting Records! ", MsgBoxStyle.Exclamation)
' End Try
cmd.Parameters.Clear()
End Using
If con.State = ConnectionState.Open Then
con.Close()
End If
答案 0 :(得分:0)
错误由SQL生成。 你确定下面的行实际返回并整数?:
Dim id As String = Me.DataGridView2.CurrentRow.Cells(0).Value
首先测试它(以下示例中的内容):
Dim g As String
Try
Dim l As Integer = Integer.Parse(g)
'If successful then save action'
Catch ex As Exception
'Warn about error'
End Try
答案 1 :(得分:0)
我解决了我的问题。问题是这个“Dim id As String = Me.DataGridView2.CurrentRow.Cells(0).Value”我刚刚在表上指定了Id_indv的确切单元格数我将其从(0)更改为(18)列所在的列我的PK被找到了。谢谢那些帮助我解决这个问题的人。 以下是其他参考的工作代码:
Dim result
Dim id As String = Me.DataGridView2.CurrentRow.Cells(18).Value
Using cmd As New SqlClient.SqlCommand
result = MsgBox(" Are You Sure You Want to Delete the Selected Row ? ", MsgBoxStyle.YesNo)
' Try
If result = Windows.Forms.DialogResult.No Then
Exit Sub
Else
If con.State = ConnectionState.Closed Then
con.Open()
End If
cmd.Connection = con
cmd.CommandText = "DELETE FROM IndvReports WHERE Id_indv = " & id
cmd.Parameters.AddWithValue("@id", id)
cmd.ExecuteNonQuery()
Me.DataGridView2.Rows.Remove(Me.DataGridView2.CurrentRow)
MsgBox(" Record Successfully Deleted! ", MsgBoxStyle.Information)
cmd.Parameters.Clear()
End If
'Catch ex As Exception
' MsgBox(" Error Deleting Records! ", MsgBoxStyle.Exclamation)
' End Try
cmd.Parameters.Clear()
End Using
If con.State = ConnectionState.Open Then
con.Close()
End If