(newbie-VB2005 EE) - filenames in ListBox

O

Opa Vito

Hi, my project needs a way to list the filenames of files of a certain
folder. To my understanding a ListBox is best for this purpose. It lists
the filenames and one can select a file and pass this name to a
string-variable for further use. That's what I intend to do anyway.

I found many examples of binding a ListBox to a database but none to a
folder .... for some strange reason it seems seldom to be used this way.
So here's my question:
How do I 'connect' a Listbox to a folder and read the filenames?

Many thanks

Vito
(from Flanders/Belgium/Europe)
 
P

Peter Proost

Hi this should do it, mind the typo's as it's out of my head:

ListBox1.Items.AddRange(Directory.GetFiles("c:\test"))

Hope this helps

Peter also from Flanders/Belgium/Europe ;-)
 
O

Olie

I guess the reason a listbox is seldom used for this task is that most
people use the OpenFileDialog control.

You may be able to directly bind to a folder using a list box but I
would just simply iterate through the files in the folder and add them
to the listbox.

dir1 = New DirectoryInfo(DirPath)
For Each Item As FileInfo In dir1.GetFiles()
listbox.Items.Add(Item.ShortName)
Next
 
O

Opa Vito

Peter Proost schreef:
Hi this should do it, mind the typo's as it's out of my head:

ListBox1.Items.AddRange(Directory.GetFiles("c:\test"))

Hope this helps

Peter also from Flanders/Belgium/Europe ;-)

Yep it works .... Thanks.

Vito
 
O

Opa Vito

Olie schreef:
I guess the reason a listbox is seldom used for this task is that most
people use the OpenFileDialog control.

You may be able to directly bind to a folder using a list box but I
would just simply iterate through the files in the folder and add them
to the listbox.

dir1 = New DirectoryInfo(DirPath)
For Each Item As FileInfo In dir1.GetFiles()
listbox.Items.Add(Item.ShortName)
Next

I changed the code to this:

Dim dir1 As New DirectoryInfo("c:\pictures")
For Each Item As FileInfo In dir1.GetFiles()
ListBox1.Items.Add(Item.Name.Substring(0, Item.Name.IndexOf(".")))
Next

and it works.

'ShortName' doesn't seem to be a member of File:IO, but please
understand I'm a newbie in programming so maybe I didn't get a few
things clear :)

Vito
 
H

Herfried K. Wagner [MVP]

Opa Vito said:
I changed the code to this:

Dim dir1 As New DirectoryInfo("c:\pictures")
For Each Item As FileInfo In dir1.GetFiles()
ListBox1.Items.Add(Item.Name.Substring(0, Item.Name.IndexOf(".")))
Next

and it works.

Check out 'System.IO.Path' and its shared methods too!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top