Hello programmers!

I am making File Browser software and I want to display icons of my files in listview. Here is the code:

ImageList1.Images.Clear()

        Dim di As New IO.DirectoryInfo(LocationA.Text)

        Dim aryFi As IO.FileInfo() = di.GetFiles("*")

        Dim fi As IO.FileInfo

        For Each fi In aryFi

            For Each files In System.IO.Directory.GetFiles(LocationA.Text)
                Dim icons As Icon = Icon.ExtractAssociatedIcon(files)
                ImageList1.Images.Add(icons)

            Next
            ListView1.Items.Add(fi.Name, ImageList1.Images.Count)

        Next

This code looks good but when I start the software I see this:

http://i.imgur.com/2hrug.png

Look at the left listview. First icon in listview loops to end.

Can anyone fix this code?

Thanks.

P.S. LocationA is Label with location of the directory!

Recommended Answers

All 4 Replies

Try this mod to your code

        ' clear the imagelist so we don't have extras
        ImageList1.Images.Clear()
        ' you need this next line to keep the ListView from flickering!
        ListView1.BeginUpdate()

        Dim di As New IO.DirectoryInfo(LocationA.Text)

        For Each fi As IO.FileInfo In di.GetFiles("*")
            ' provide a default icon in case we can't extract one
            Dim icons As Icon = SystemIcons.WinLogo
            ' set that default as the new listitem's icon
            Dim li As New ListViewItem(fi.Name, 1)
            ' check ImageList to see if we have an icon for this file type
            If Not (ImageList1.Images.ContainsKey(fi.Extension)) Then
                ' we don't, let's try to get one
                icons = System.Drawing.Icon.ExtractAssociatedIcon(fi.FullName)
                ImageList1.Images.Add(fi.Extension, icons)
            End If
            icons = Icon.ExtractAssociatedIcon(fi.FullName)
            ImageList1.Images.Add(icons)
            ListView1.Items.Add(fi.Name, fi.Extension)
        Next

        ' all done, redraw the listview
        ListView1.EndUpdate()

It works! Thanks! :D

Of course it works, if it was untested code I would've said so! :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.