【发布时间】: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 我是使用编程这一方面的新手,所以可以预见我走了很长的路。我可以在那里使用任何资源或示例吗?我做了一些研究并想出了这段代码,但我可能正在寻找错误的东西。