Compare datagridview VB

0

I have a form with 3 datagridview.

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

How do you compare and load dgv3 products only on dgv1 products that do not appear on dgv2?

In short, I would like the third datagridview to be the difference between the two previous ones.

    
asked by anonymous 17.03.2017 / 13:17

2 answers

0

Roughly, this would be:

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 is not the best way to do this. If DataGridViews data comes from DataSources, it would be better for you to do this analysis directly on the data objects.

    
23.03.2017 / 22:01
0

Answering your question

Just scroll through the first DataGridView, comparing item to 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'd better do this when you fetch the data, either in DataSource or in another mode. Because you avoid making these comparisons with DataGridViews.

    
19.05.2017 / 15:07