我有一个带有复选框列的数据网格,用户可以选择要删除的记录。由于有多个值,我构建一个用逗号分隔的字符串列表,然后在循环中删除一次。但是,仅删除第一个选定值,代码忽略其余值。
我但我的变量在消息框上,第一个值单独显示,但之后的任何内容都显示在一行而不是分开。
我已多次查看此代码,但我看不出我的错误。
这是我检查所选行的循环。
Private Sub btnDeleteRecord_Click(sender As Object, e As EventArgs) Handles btnDeleteRecord.Click
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)
'Call procedure to delete multiple records
DeleteMultipleRecords(idCollection)
End If
Next
Catch ex As Exception
MsgBox(ex.ToString())
End Try
End Sub
Here is the procedure where the records get deleted
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
Cursor.Current = Cursors.WaitCursor
**DataSheetTableAdapter.DeleteRecord(strIDs)** 'This is only deleting the first value
Cursor.Current = Cursors.Default
Catch ex As Exception
Dim errorMsg As String = "Error in Deletion"
errorMsg += ex.Message
Throw New Exception(errorMsg)
Finally
End Try
End Sub
答案 0 :(得分:1)
我相信您的问题是,当您只想调用一次时,您多次调用DeleteMultipleRecord
子。我想您可能希望迭代数据网格,收集所有已检查的行,并在收集完所有行后,仅执行一次删除操作。
我只是将删除操作移到了行迭代循环之外,因为它旨在一次删除很多东西。
Private Sub btnDeleteRecord_Click(sender As Object, e As EventArgs) Handles btnDeleteRecord.Click
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)
'Call procedure to delete multiple records
'DeleteMultipleRecords(idCollection)
End If
Next
' moved to here.
DeleteMultipleRecords(idCollection)
Catch ex As Exception
MsgBox(ex.ToString())
End Try
End Sub