Search code examples
.netvb.netbasic

update ListView from another form


I tried all methods by users here but none seems to work for me. I want to update a ListView in Form1 from Form2 in vb.net but nothing happens when I launch this method.

Public Sub checkFoundList()
    For Each item In myListView.Items
        If Not File.Exists(item.SubItems(2).Text) Then
            myListView.Items.Remove(item)
        End If
    Next
End Sub

This method is on Form1 and when I launch it here it works fine. But if I call it from Form2, it doesn't.

In Form2 I just call it with:

Form1.checkFoundList()

I tried also to put the modifier Public to myListView but still doesn't work. Also the methods explained by some users like using events doesn't work. Really weird.

Is ListView a special control?


Solution

  • One problem you will have is you are modifying the items in the list as you are enumerating it with a For Each statement. This will cause problems when you delete an item.

    Instead enumerate it with a For statement working backwards so the indexes don't shift when you are removing an item:

    Public Sub checkFoundList()
        For i = myListView.Items.Count - 1 To 0 Step -1
            Dim item As <TypeTheListViewHolds> = myListView.Items(i)
            If Not File.Exists(item.SubItems(2).Text) Then
                myListView.Items.RemoveAt(i)
            End If
        Next
    End Sub
    

    I have just adapted the code you provided (without knowing what myListView holds), but the methodology would be the same regardless of the datatype.

    With regards to calling it from Form2, make sure you are calling checkFoundList from an instance of Form1. Something like:

    ' Class variable in Form2 which has an instance of Form1.
    Private _form1 As Form1
    
    ' New Form2 method.
    ' Pass an instance of Form1 to the constructor of Form2.
    ' This way this instance of Form2 will "know" about a Form1 object.
    Public Sub New(form1Object As Form1)
       ' Initialization code.
    
       ' Set the reference to Form1 in Form2
       _form1 = form1Object
    End Sub
    
    Public Sub Form2Method()
        _form1.checkFoundList
    End Sub