【问题标题】:Deleting multiple selected values from datagrid. Only first value is being deleted从数据网格中删除多个选定的值。只有第一个值被删除
【发布时间】:2014-01-17 01:22:29
【问题描述】:

我有一个带有复选框列的数据网格,用户可以在其中选择要删除的记录。由于有多个值,我构建了一个用逗号分隔的字符串列表,然后通过循环一次删除一个。但是,只有第一个选定的值被删除,代码忽略了剩余的值。

但我的变量在消息框上,第一个值单独出现,但之后的任何内容都显示在一行上并且没有分隔。

我已经多次查看此代码,但我看不出哪里出错了。

这是我检查选定行的循环。

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

【问题讨论】:

    标签: vb.net datagridview


    【解决方案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
    

    【讨论】:

      猜你喜欢
      • 2012-03-13
      • 1970-01-01
      • 1970-01-01
      • 2020-06-08
      • 1970-01-01
      • 1970-01-01
      • 2022-12-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多