Results 1 to 3 of 3

Thread: Comparing Listview boxes

  1. #1

    Thread Starter
    Addicted Member
    Join Date
    Nov 2007
    Posts
    134

    Comparing Listview boxes

    I have two listview boxes. I want my program to go through each row of ListView1 column 5, Comparing it with each row in column 5 of Listview2 and if there is no match then delete the row from Listview1. What would be the best way to go about doing this?

  2. #2
    Fanatic Member
    Join Date
    Mar 2009
    Posts
    804

    Re: Comparing Listview boxes

    Code:
    Option Explicit
    Private Sub Form_Load()
    'add Cols
     Dim i As Long, j As Long
     For i = 1 To 5
      With ListView1.ColumnHeaders.Add
       .Text = "C" & i
       .Width = ListView1.Width \ 5
      End With
      With ListView2.ColumnHeaders.Add
       .Text = "C" & i
       .Width = ListView1.Width \ 5
      End With
     Next
     'add same data to both LVs
     For i = 1 To 5
      With ListView1.ListItems.Add
       .Text = "R" & i & " C1"
       For j = 1 To 4
        .SubItems(j) = "R" & i & "C" & j + 1
       Next
      End With
      With ListView2.ListItems.Add
       .Text = "R" & i & "C1"
       For j = 1 To 4
        .SubItems(j) = "R" & i & "C" & j + 1
       Next
      End With
     Next
    End Sub
    'Here we expect all items in LV1 to be deleted
    'since they have the same data as LV2
    Private Sub Command1_Click()
     Dim i As Long
     'when removing LV items, always step backwards
     For i = ListView1.ListItems.Count To 1 Step -1
      With ListView1.ListItems(i)
       If .SubItems(4) = ListView2.ListItems(i).SubItems(4) Then
        ListView1.ListItems.Remove i
       End If
      End With
     Next
    End Sub

  3. #3
    PowerPoster RhinoBull's Avatar
    Join Date
    Mar 2004
    Location
    New Amsterdam
    Posts
    24,132

    Re: Comparing Listview boxes

    You'd have to loop through ListItems collection and compare subitems.
    Here is a very quick sample (made entirely from memory):
    Code:
    Dim i As Integer
    Dim j As Integer
    Dim blnFound As Boolean
    
        For i = Listview1.ListItems.Count To 1
            blnFound = False
            For j = 1 To Listview1.ListItems.Count
                If Listview1.ListItems(i).SubItems(4) = Listview2.ListItems(j).SubItems(4) Then
                    blnFound = True
                End If
            Next j
            If Not blnFound Then
                Listview1.ListItems.Remove i
            End If
        Next i
    Note: verify all syntax before running (press CTRL+F5 to full compile code first).

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width