首页 > 解决方案 > 如果行在datagridview中有值,则在下一行插入数据

问题描述

我有两个datagridview,在dgv1中我有一个按钮,可以删除选定的行并将选定的行传输到我的第二个dgv2,问题是,在我第二次删除一行时,它会覆盖我删除的行

我尝试了多个代码,但最终出现了同样的问题

Dim row As New DataGridViewRow
Dim nextrow As New DataGridViewRow
   For Each row In DataGridView3.Rows
   For Each nextrow In DataGridView3.Rows


    If row.Index <> nextrow.Index Then
    If row.Cells(0).Value = nextrow.Cells(0).Value AndAlso 
    row.Cells(2).Value = nextrow.Cells(2).Value AndAlso row.Cells(3).Value 
    = nextrow.Cells(3).Value AndAlso row.Cells(8).Value = 
    nextrow.Cells(8).Value Then

    DataGridView3.Rows.Remove(row)
    DataGridView3.Rows.Remove(nextrow)

    End If
    End If

      Next

    Next

它在第一次尝试时有效,但在第二次它会覆盖我的 dgv2 中的数据我想显示从我的 dgv1 到 dgv2 的已删除数据

标签: vb.net

解决方案


当您使用集合并删除项目时,一种好的技术是向后而不是向前遍历集合。这是因为如果您删除/删除集合中的一项,它可以更改集合。例如,您删除了第 4 项,因此第 5 项变为第 4 项,然后您尝试对第 5 项执行某些操作,但现在是第 6 项,等等。

要消除此问题,请尝试以下操作:

Dim myrows As Integer = gvw.rows.count
Dim row as GridViewRow, rownext as GridViewRow
For myrow As Integer = myrows -1  To 0 Step -1
  row = gvw.rows(myrow)
  rownext gvw.rows(myrow - 1)

  'Do some comparison

  If .. Then
    gvw.rows.Remove(myrow) 'you can remove it because it is the last row
  End If
  If myrow = 1 Then Exit For 'cannot go lower
Next

推荐阅读