无法删除多条记录

时间:2012-08-08 04:06:35

标签: asp.net vb.net

我已编写代码来删除gridview中的多个记录,但它只删除gridview中的一条记录。有人可以帮我解决这个问题。这是我的代码

 'This is to Delete multiple records in gridview
Private Sub DeleteMultipleRecords(ByVal idCollection As StringCollection)
    'Create sql Connection and Sql Command
    Dim cnnOLEDB As New OleDbConnection(strConnectionString)
    Dim cmd As New OleDbCommand()
    Dim IDs As String = ""

    'Create string builder to store 
    'delete commands separated by ;

    For Each id As Integer In idCollection
        IDs += id & ","
    Next
    Try
        Dim test As Integer = IDs
        Dim sql As String = "DELETE FROM [1BK] WHERE [sampleID] in (" & test & ")"
        Dim ANS As Integer
        ANS = MsgBox("Are you sure want to delete selected record ?" & vbCrLf & vbCrLf, MsgBoxStyle.YesNo)
        If ANS = vbYes Then
            cmd.CommandType = CommandType.Text
            cmd.CommandText = sql
            cmd.Connection = cnnOLEDB
            cnnOLEDB.Open()
            cmd.ExecuteNonQuery()
        End If
        ANS = 0
    Catch ex As Exception
        Dim errorMsg As String = "Error in Deletion"
        errorMsg += ex.Message
        Throw New Exception(errorMsg)
    Finally
        cnnOLEDB.Close()
    End Try
End Sub

3 个答案:

答案 0 :(得分:0)

当您使用string子句时,测试变量应为IN。 例如

string test="'1','2'"
if(test=="")
 test = "'" & id & "'"
else
 test += "," & "'" & id & "'"

然后查询将起作用

答案 1 :(得分:0)

使用以下代码

IDs+= "'"&id &"'" & ","

而不是

IDs += id & ","

答案 2 :(得分:0)

您的代码存在问题。

//Dim test As Integer
Dim test As String

test是一个字符串值,而不是整数。

当你完成

IDs += id & ","

最后一个“,”应该删除。

所以你应该在完成循环后再添加一行代码。

IDs = IDs.TrimEnd(',')