vb.netlistboxdatasourcegetfilesgetdirectories

How I Fill listbox from 2 different sources (folders/directories)?


I'm trying to sort some documents into a listbox, If my document is a collection scanned pictures into folders, it must list at lisbox1 each folder, if my document is a .pdf it must be added too

directo = "D:\books\

ListBox1.DataSource = IO.Directory.GetDirectories(directo, "*.*", IO.SearchOption.TopDirectoryOnly)
ListBox1.DataSource = IO.Directory.GetFiles(directo, "*.pdf", IO.SearchOption.TopDirectoryOnly)

I get as result:

D:\books\Book-A

D:\books\Book-B

D:\books\Book-C

or

D:\books\Book-E.pdf

D:\books\Book-F.pdf

D:\books\Book-G.pdf

but i can't get it mixed, eachtime the listbox show me just one source or another. Any suggestion to list?


Solution

  • You can convert the return values of GetDirectories and GetFiles to a List(Of String), and then merge the two together. This merged list can then be assigned to the DataSource property of the ListBox. See below for an example.

    Dim directories As List(Of String) = Directory.GetDirectories(directo, "*.*", SearchOption.TopDirectoryOnly).ToList()
    Dim files As List(Of String) = Directory.GetFiles(directo, "*.pdf", SearchOption.TopDirectoryOnly).ToList()
    
    Dim dataSourceList As New List(Of String)
    dataSourceList.AddRange(directories)
    dataSourceList.AddRange(files)
    
    ListBox1.DataSource = dataSourceList