【问题标题】:Deleting Multiple records from Datagrid using a String Collection使用字符串集合从 Datagrid 中删除多条记录
【发布时间】:2014-02-10 09:53:56
【问题描述】:

我已经构建了一个带有复选框列的数据网格,以便用户可以选择要删除的记录。我发过一个类似的 几天前的问题。

我只是设法让程序工作了一半。仅当一条记录时,我的书面程序才会删除 被选中。它不会删除整个列表。这是我的用户界面:

这是我的代码:

    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 子上放了一个消息框,这是显示:

我认为问题在于我的DataSheetTableAdapter.DeleteRecord(strIDs) 没有在每个逗号之后分隔记录并遍历每个记录并删除。 有人可以告诉我这里哪里出错了吗?

【问题讨论】:

  • 您需要发布删除操作的代码。但是,鉴于您使用的是 tableadapter,为什么不通过 bindingsource 将网格绑定到数据集,将每个选中的行标记为已删除,然后在 tableadapter 上调用更新?
  • 就像我看到的许多人一样,您不使用 DataTable 和数据绑定会让这件事变得更加困难。使用表适配器填充 DataTable 并将其绑定到网格。然后,您可以遍历检查行并在基础 DataRow 上调用 Delete。删除所有行后,您可以在表适配器上调用 Update,所有这些更改都将一次性保存到数据库中。
  • @jmcilhinney 我是使用编程这一方面的新手,所以可以预见我走了很长的路。我可以在那里使用任何资源或示例吗?我做了一些研究并想出了这段代码,但我可能正在寻找错误的东西。

标签: vb.net datagrid


【解决方案1】:

我会将其发布为答案而不是评论,以便我可以包含代码。

1- 将您的复选框列添加到设计器的网格中。我假设您已经知道如何操作,但如果您不知道,请告诉我们。

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

myAdapter.Fill(myDataTable)
Me.BindingSource1.DataSource = myDataTable
Me.DataGridView1.DataSource = Me.BindingSource1

如果您使用的是类型化 DataSet,那么您可以在设计器中设置绑定。

3- 选中相应的框后,从绑定的 DataTable 中删除相应的行。

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)

【讨论】:

    【解决方案2】:

    使用连接模式,您可以根据所选的 TicketNumber 循环遍历 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
    

    【讨论】:

      猜你喜欢
      • 2020-08-27
      • 2014-02-02
      • 1970-01-01
      • 2010-11-02
      • 1970-01-01
      • 2021-07-15
      • 1970-01-01
      • 2018-01-27
      • 1970-01-01
      相关资源
      最近更新 更多