[RESOLVED] [2005] Listbox Items = Folder Contents
Hi everyone,
I have a form which contains a listbox and I want it to display the names of the files in a certain folder.
Basically what I need is for items in the listbox to be the name of text files in a folder.
I have tried several methods involving the stream-reader but with that, each file has to be specified individually and since the user creates new files any time this wouldn't work.
Can anyone provide any hints or suggestions.
Re: [2005] Listbox Items = Folder Contents
Alter this to suit you.
Code:
For Each sFile As String In IO.Directory.GetFiles("C:\", "*.txt", IO.SearchOption.TopDirectoryOnly)
ListBox1.Items.Add(IO.Path.GetFileName(sFile))
Next
Re: [2005] Listbox Items = Folder Contents
user name's code will work but it's not optimal. If you're going to add items one at a time you should call BeginUpdate first.
Code:
Me.ListBox1.BeginUpdate()
For Each file As String In IO.Directory.GetFiles("folder path here", "*.txt")
Me.ListBox1.Items.Add(IO.Path.GetFileName(file))
Next file
Me.ListBox1.EndUpdate()
Code:
Dim files As String() = IO.Directory.GetFiles("folder path here", "*.txt")
For index As Integer = 0 To files.GetUpperBound(0) Step 1
files(index) = IO.Path.GetFileName(files(index))
Next index
Me.ListBox1.Items.AddRange(files)
Code:
Dim files As String() = IO.Directory.GetFiles("folder path here", "*.txt")
For index As Integer = 0 To files.GetUpperBound(0) Step 1
files(index) = IO.Path.GetFileName(files(index))
Next index
Me.ListBox1.DataSource = files
Re: [2005] Listbox Items = Folder Contents
Wow Thanks Guys :)
The code worked perfectly.
Note to others, if you just want the file name without the extension, just use GetFileNameWithoutExtension as shown below.
Code:
Me.ListBox1.BeginUpdate()
For Each file As String In IO.Directory.GetFiles(path & "\Favorites\")
Me.ListBox1.Items.Add(IO.Path.GetFileNameWithoutExtension(file))
Next file
Me.ListBox1.EndUpdate()