在两个DGV

时间:2017-05-13 15:21:19

标签: vb.net loops datagridview duplicates nested-loops

我花了很多时间在这上面并且无处可去。我有两个DGV,并试图比较两个列的相同值,如果DGV2中的值不在DGV1中,那么该值应该转到DGV3。这里的问题是合乎逻辑的,但是长时间主持这个错误的解决方案使我无法继续前进。

在我看来,整个DGV1应该在IF之前在DGV2中搜索第一个值,并且在DGV2中搜索其他所有值。我不知道我真的需要帮助。

感谢。

 Dim row As String() = New String() {"", "", "", ""}
    Dim x As Integer = 0
    For A = 0 To DGV2.RowCount - 1
        For B = 0 To DGV1.RowCount - 1
            If GetTextOrEmpty(DGV1.Rows(A).Cells(4).Value) = GetTextOrEmpty(DGV2.Rows(B).Cells(1).Value) Then
            Else
                'PROBLEM : This is going to add row WITH SAME VALUES everytime it's <>
                DGV3.Rows.Add(row)
                DGV3.Rows(x).Cells(0).Value = DGV2.Rows(B).Cells(0).Value
                DGV3.Rows(x).Cells(1).Value = DGV2.Rows(B).Cells(2).Value
                DGV3.Rows(x).Cells(2).Value = DGV2.Rows(B).Cells(1).Value
                DGV3.Rows(x).Cells(3).Value = DGV2.Rows(B).Cells(3).Value
                x = x + 1
            End If
        Next
    Next

编辑:没关系。问题解决了这个问题:

  Dim row As String() = New String() {"", "", "", ""}

    Dim x As Integer = 0
    For A = DGV2.RowCount - 1 To 0 Step -1
        For B = 0 To DGV1.RowCount - 1
            If GetTextOrEmpty(DGV1.Rows(B).Cells(4).Value) = GetTextOrEmpty(DGV2.Rows(A).Cells(1).Value) Then
                DGV2.Rows.Remove(DGV2.Rows(A))
            End If
        Next
    Next

    For i = 0 To DGV2.RowCount - 1
        DGV3.Rows.Add(row)
        DGV3.Rows(x).Cells(0).Value = DGV2.Rows(i).Cells(0).Value
        DGV3.Rows(x).Cells(1).Value = DGV2.Rows(i).Cells(2).Value
        DGV3.Rows(x).Cells(2).Value = DGV2.Rows(i).Cells(1).Value
        DGV3.Rows(x).Cells(3).Value = DGV2.Rows(i).Cells(3).Value
        x = x + 1
    Next

1 个答案:

答案 0 :(得分:1)

使用HashSet加快一点:

Dim values = New HashSet(Of String)(From i In Enumerable.Range(0, DGV1.RowCount) 
                                    Select Convert.ToString(DGV1(4, i).Value))

For Each r As DataGridViewRow In DGV2.Rows
    If Not values.Contains(Convert.ToString(r.Cells(0).Value)) Then
        DGV3.Rows.Add(r.Cells(0).Value, r.Cells(1).Value, r.Cells(2).Value, r.Cells(3).Value)
    End If
Next