Vb.net 使用字符串集合从Datagrid中删除多个记录

Vb.net 使用字符串集合从Datagrid中删除多个记录,vb.net,datagrid,Vb.net,Datagrid,我构建了一个带有复选框列的datagrid,以便用户可以选择要删除的记录。我曾发布过类似的帖子 几天前的问题 我只是设法使程序进行了一半。我写的过程只删除一条记录 被选中。它不会删除整个列表。这是我的用户界面: 这是我的密码: Private Sub btnDeleteRecord_Click(sender As Object, e As EventArgs) Handles btnDeleteRecord.Click 'This procedure deletes th

我构建了一个带有复选框列的datagrid,以便用户可以选择要删除的记录。我曾发布过类似的帖子 几天前的问题

我只是设法使程序进行了一半。我写的过程只删除一条记录 被选中。它不会删除整个列表。这是我的用户界面:

这是我的密码:

    Private Sub btnDeleteRecord_Click(sender As Object, e As EventArgs) Handles btnDeleteRecord.Click
       'This procedure deletes the selected ticket number
       'from the DataSheet table. The procedure refreshes
       'the Datasheet table and the labels in the frmMainForm
      Dim idCollection As New StringCollection()
      Dim strID As String = String.Empty
        Try
        'Store each selected record on string collection
           For Each row As DataGridViewRow In grdDeleteRecord.Rows
             If row.Cells(0).Value() Then
               strID = row.Cells(1).Value()
               idCollection.Add(strID)
             End If
            Next
        'Call procedure to delete multiple records
        DeleteMultipleRecords(idCollection)
        Catch ex As Exception
           MsgBox(ex.ToString())
        End Try
      End Sub
  Private Sub DeleteMultipleRecords(ByVal idCollection As StringCollection)
     Dim IDs As String = ""
     'Create string builder to store 
     'delete commands separated by ;
       For Each id As String In idCollection
         IDs += id.ToString() & ","
       Next
      Try
        Dim strIDs As String = IDs.Substring(0, IDs.LastIndexOf(","))
        Dim strPrompt As String = "Record deletion cannot be undone. Are you sure you want to delete the record?"
        Dim strTitle As String = "Delete Record"
        Dim msgProceed As MsgBoxResult
      'Warn the user that records cannot be undone
        msgProceed = MsgBox(strPrompt, CType(MsgBoxStyle.YesNo + MsgBoxStyle.Critical, MsgBoxStyle), strTitle)
      If msgProceed = MsgBoxResult.Yes Then
      'Local variables
         Dim strTicketNumber As String = txtTicketNumber.Text
         Dim todayDate As Date = Date.Now
         Dim beginWeek As Date = Public_Subs.MondayOfWeek(todayDate).Date
         Dim endOfWeek As Date = beginWeek.AddDays(6)
         Dim strBeginDay As String = todayDate.ToShortDateString & " 12:00:00 AM"
         Dim strEndDay As String = todayDate.ToShortDateString & " 11:59:59 PM"
         Cursor.Current = Cursors.WaitCursor
         DataSheetTableAdapter.DeleteRecord(strIDs)
      Else
         btnClear.Visible = False
         btnDeleteRecord.Enabled = False
      End If
      Catch ex As Exception
        Dim errorMsg As String = "Error in Deletion"
        errorMsg += ex.Message
        Throw New Exception(errorMsg)
       Finally
      End Try
End Sub
我在DeleteMultipleRecords子菜单上放置了一个消息框,显示如下:

我认为问题在于我的
数据表TTabalAdapter.DeleteRecord(strIDs)
没有将每个逗号后的记录分开,并遍历每个记录并删除。
有人能告诉我哪里出了问题吗?

我将把这篇文章作为答案而不是评论,这样我就可以包含代码了

1-将复选框列添加到设计器中的网格中。我想你已经知道怎么做了,但是如果你不知道,请告诉我们

2-填充DataTable并通过BindingSource将其绑定到网格

myAdapter.Fill(myDataTable)
Me.BindingSource1.DataSource = myDataTable
Me.DataGridView1.DataSource = Me.BindingSource1
如果使用的是类型化数据集,则可以在设计器中设置绑定

3-选中相应的框后,从绑定数据表中删除相应的行

Dim rowsToDelete = (From row In Me.DataGridView1.Rows.Cast(Of DataGridViewRow)()
                    Where CBool(row.Cells(0).Value)
                    Select row.DataBoundItem).Cast(Of DataRowView)().ToArray()

For Each row In rowsToDelete
    row.Delete()
Next
这可以通过其他方式实现,无论是否使用LINQ,但你希望你能得到这个想法

4-使用相同的数据/表适配器将所有更改保存回数据库

myAdapter.Update(myDataTable)

使用连接模式,可以循环浏览DataGridView选定的行,并根据选定的票号从数据库中删除

Private Sub DeleteSelected(ByVal UserSelectedID As Integer)
  Using CN As New OleDbConnection With {.ConnectionString = GetBuilderCNString()}
                CN.Open()
                Dim SqlStr As String =
                            ("DELETE * FROM Tickets WHERE TicketNumber=?")
                    Using DelCMD As New OleDbCommand With _
{.Connection = CN, .CommandType = CommandType.Text, .CommandText = SqlStr}
                    Try
                        Dim I As Integer = 0
                        For Each Irow As DataGridViewRow In DisplayDGV.SelectedRows
                            UserSelectedID = Irow.Cells(0).Value 'TicketNumber
                            With DelCMD.Parameters
                                .Add("?", OleDbType.BigInt).Value = UserSelectedID
                            End With
                            DelCMD.ExecuteNonQuery()
                            DelCMD.Parameters.Clear()
                            I += 1
                        Next
                        LblStatus.Text = (I & " Deleted successfully.")
                    Catch ex As OleDbException
                        Debug.WriteLine("Delete Error : " & ex.Message)
                    End Try
                End Using
            End Using
End Sub

您需要发布删除操作的代码。但是,既然您使用的是tableadapter,为什么不通过bindingsource将网格绑定到数据集,将每个选中的行标记为已删除,然后在tableadapter上调用update?就像我看到的许多人一样,您不使用DataTable和数据绑定,这会让您自己更加困难。使用表适配器填充数据表并将其绑定到网格。然后,您可以循环检查行,并对基础数据行调用Delete。删除所有行后,在表适配器上调用Update,所有这些更改都将在一个批中保存到数据库中。@jmcilhinney我对使用编程的这一方面还不熟悉,所以可以预见,我走了很长的路。有没有我可以使用的资源或示例?。我做了一些研究,并提出了这个代码,但我可能是在寻找错误的东西。