Search code examples
vb.netwinformslistviewimagelist

How do I set images to listview items when they contain certain text?


Does anyone know how I set images to items when they contain certain text? For instance if an items' text is something with ".png" I want to give that item (or those items) an image which I've added to an . Here is the code I use to populate the with folders and files:

    Dim FilePath As String = "C:\"
    ControlListView.Items.Clear()
    Dim DirInfo() As DirectoryInfo

    DirInfo = New DirectoryInfo(FilePath).GetDirectories

    For Each DirInfoFolder In DirInfo
        ControlListView.Items.Add(DirInfoFolder.Name)
    Next

    Dim FilePathFiles As New IO.DirectoryInfo(FilePath)

    For Each FileInfoFolder In FilePathFiles.GetFiles
        ControlListView.Items.Add(FileInfoFolder.Name)
    Next

Any help would be appriciated. Thanks in advance :)


Solution

  • Instead of using the default ListView.Add(string), you need to construct your own ListViewItem and then add it to the ListView after setting the correct index for the image in the image list. (My VB.Net is rusty so please verify the syntax)

    For Each FileInfoFolder In FilePathFiles.GetFiles
        Dim lvi as New ListViewItem(FileInfoFolder.Name)
    
        If FileInfoFolder.Name.EndsWith(".png")
            lvi.ImageIndex = pngImageIndex
        End If
    
        ControlListView.Items.Add(lvi)
    Next