user3688529
user3688529

Reputation: 97

vb.net ~ How to add folder names from a directory to a list box

I'm trying to add folder names from within a directpory specified by the user to a list box. I have tried a few solutions, but can't seem to add any items. Most recently I tried:

For Each folder As String In System.IO.Path.GetDirectoryName("D:\")
    ListBox1.Items.Add(folder)
Next

The form was built using VB in VB Studio Express 2013. There were no errors when running the program.

If anyone can point me in the right direction, then please help!

Upvotes: 2

Views: 8883

Answers (2)

Muhammad Jana
Muhammad Jana

Reputation: 1

how to select folder name to preview picture

Imports System.IO

Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    For Each folder As String In System.IO.Directory.GetDirectories("C:\Program Files (x86)\KONAMI\Pro Evolution Soccer 2016\SFXPath\SweetFX")
        ListBox1.Items.Add(Path.GetFileName(folder))

    Next
End Sub
Private Sub ListBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ListBox1.SelectedIndexChanged


    If ListBox1.SelectedItem = "folder" Then PictureBox1.ImageLocation = "C:\Program Files (x86)\KONAMI\Pro Evolution Soccer 2016\SFXPath\SweetFX\HD Natural by pimplo\preview.jpg"
End Sub
End Class

Upvotes: 0

Steve
Steve

Reputation: 216293

If you want to have a list of Directories you need to call Directory.GetDirectories(path), not Path.GetDirectoryName(path) that, in your case returns just null (passing the root directory of a drive)

For Each folder As String In System.IO.Directory.GetDirectories("D:\")
    ListBox1.Items.Add(folder)
Next

if you want to show only the folder name and not the full path, just use

For Each folder As String In System.IO.Directory.GetDirectories("D:\")
    ListBox1.Items.Add(Path.GetFileName(folder))
Next

Yes, I know, it seems wrong to ask for GetFileName over a folder name, but passing a full path to GetFileName returns just the folder without the path.

Upvotes: 3

Related Questions