标准表达式错误

时间:2014-11-16 22:15:01

标签: vb.net datagridview mismatch

我刚刚完成了一个关于使用复选框从datagridview删除数据的教程,除了我不断收到此错误外,一切都很棒

  

数据类型不匹配是标准表达式

它不会删除突出显示result = cmd.ExecuteNonQuery行并显示

的任何内容
  

未处理的类型' System.Data.OleDb.OleDbException'   发生在System.Data.dll中的附加信息:数据类型不匹配   在标准表达中。

这是代码。

Private Sub btnDeleteAll_Click(sender As Object, e As EventArgs) Handles btnDeleteAll.Click
        Try
            con.Open()
            For Each row As DataGridViewRow In DataGridView1.Rows
                If row.Cells(0).FormattedValue = True Then
                    sql = "DELETE FROM tT WHERE ID = '" _
                    & CStr(row.Cells(1).FormattedValue) & "'"
                    With cmd
                        .Connection = con
                        .CommandText = sql
                    End With
                    result = cmd.ExecuteNonQuery
                End If
            Next
            If result = 0 Then
                MsgBox("nope")
            Else
                MsgBox("deleted.")
            End If
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
        con.Close()
End Sub

1 个答案:

答案 0 :(得分:0)

此方法使用参数化查询,并假设数据库中的ID字段不是字符串而是数字值(例如整数)

' Prepare the command string with the parameter placeholder
' Note that you don't need to put quotes around the placeholder
sql = "DELETE FROM tT WHERE ID = ?"

' Prepare the command creating a parameter with a initial zero value
' The AddWithValue receives an integer constant so the parameter will be created
' of Integer type. Note that this shortcut is dangerous and it is better to 
' explicity create the parameter with your chosen type.
With cmd
   .Connection = con
   .CommandText = sql
   .Parameters.AddWithValue("@p1", 0)
End With

' Loop over your rows, place the correct value into the parameter and execute
' I don't like to use CInt or CStr from VB6 heritage and prefer to use the 
' framework methods Convert.ToXXXXX but I suppose that CInt works as well here.
For Each row As DataGridViewRow In DataGridView1.Rows
    If row.Cells(0).FormattedValue = True Then
        cmd.Parameters("@p1").Value = Convert.ToInt32(row.Cells(1).FormattedValue)
        result = cmd.ExecuteNonQuery
    End If
Next