Search code examples
vb.netdatagridviewdatagridviewcolumn

Removing duplicate data out of column datagridview vb.net


I've looked all around and haven't found a answer :/

screenshot: http://prntscr.com/9257cg

I want that entry to only show up once and not stay there (the "to" column), basically remove the duplicates. Here is my update code

Private Sub datagridview1Update()

    'Remove rows if there are too many
    If DataGridView1.Rows.Count > 9 Then
        DataGridView1.Rows.RemoveAt(0)
    End If

    DataGridView1.Rows.Add()
    DataGridView1.Rows(DataGridView1.Rows.Count - 2).Cells(0).Value = ipfrom.ToString 'From Column, size at 125
    DataGridView1.Rows(DataGridView1.Rows.Count - 2).Cells(1).Value = ipto.ToString  'To Column, size at 125
    DataGridView1.Rows(DataGridView1.Rows.Count - 2).Cells(2).Value = destinationport.ToString
    DataGridView1.Rows(DataGridView1.Rows.Count - 2).Cells(3).Value = sourceport.ToString

End Sub

Solution

  • First you should loop through your DataGridView1's Rows to see if there is already an entry that matches the new data. Add the new row if no match is found. Also, you should only subtract one from the count of rows to keep correct ordering.

    Private Sub datagridview1Update()
    
        Dim bolFoundMatch As Boolean = False
        Dim intCursor As Integer = 0
    
        Do Until bolFoundMatch OrElse intCursor = DataGridView1.Rows.Count
    
            If DataGridView1.Rows(intCursor).Cells(1).Value = ipto.ToString() Then
    
                bolFoundMatch = True
    
            End If
    
            intCursor += 1
    
        Loop
    
        If Not bolFoundMatch Then
    
            'Remove rows if there are too many
            If DataGridView1.Rows.Count > 9 Then
                DataGridView1.Rows.RemoveAt(0)
            End If
    
            DataGridView1.Rows.Add()
            DataGridView1.Rows(DataGridView1.Rows.Count - 1).Cells(0).Value = ipfrom.ToString 'From Column, size at 125
            DataGridView1.Rows(DataGridView1.Rows.Count - 1).Cells(1).Value = ipto.ToString  'To Column, size at 125
            DataGridView1.Rows(DataGridView1.Rows.Count - 1).Cells(2).Value = destinationport.ToString
            DataGridView1.Rows(DataGridView1.Rows.Count - 1).Cells(3).Value = sourceport.ToString   
    
        End If
    
    End Sub