Compare datagridview VB

Asked

Viewed 172 times

0

I have a form with 3 datagridview.

dgv1 and dgv2 will carry a product code in column 01. dgv1 is the master, it has all products. dgv2 will only have some of these products.

How to compare them and click on dgv3 only dgv1 products that do not appear in dgv2?

In short, I would like the third datagridview to result in the difference between the previous two.

2 answers

0


Roughly speaking, that would be it:

Sub Extrair(dgv1 As DataGridView, dgv2 As DataGridView, dgv3 As DataGridView)
    Dim todosOsCodigos = dgv1.Rows.Cast(Of DataGridViewRow).Select(
        Function(dgvr) dgvr.Cells(1).Value).ToArray

    Dim codigos_dgv2 = dgv2.Rows.Cast(Of DataGridViewRow).Select(
        Function(dgvr) dgvr.Cells(1).Value).ToArray

    Dim codigos_restantes = todosOsCodigos.Except(codigos_dgv2).ToArray

    For Each dgvr As DataGridViewRow In dgv1.Rows
        If codigos_restantes.Contains(dgvr.Cells(1).Value) Then
            dgv3.Rows.Add(dgvr.Cells.Cast(Of DataGridViewCell).Select(
                Function(dgvc) dgvc.Value).ToArray)
        End If
    Next
End Sub

But it’s not the best way to do it. If Datagridviews data comes from Datasources, it would be preferable for you to perform this analysis directly on the source objects of the data.

0

To answer your question

Just go through the first Datagridview, comparing item by item with the second Datagridview. If the item does not exist, it will be added in DGV3.

Dim exite As Boolean
For Each colunas1 As DataGridViewRow In dgv1.DataGridView.Rows
    exite = False
    For Each colunas2 As DataGridViewRow In dgv2.DataGridView.Rows
        if colunas1.Cells(0).Value = colunas2.Cells(0).Value then
            existe = True
            exit For
        end if 
    Next  
    if Not exite then
        'Adiciona linha no DGV3
    end if
Next

Best solution in my opinion

I think you better do this when you search for the data, whether it is in Datasource or otherwise. Because it avoids making these comparisons with the Datagridviews.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.