Looping through each file in directory
Hi,
I have a number of bmp files in a directory, I want to loop through on the click of a button so they in turn display in the picture.image property. I have the code below which displays the first bmp correctly, how do I loop through the rest on each click of the button?
Me.Picture1.Image = System.Drawing.Image.FromFile("C:\files\" & pageCount & ".bmp")
Many thanks for the help
Steven :wave:
Re: Looping through each file in directory
How about...
VB Code:
'Assuming that your filenames are named numerically starting with 0.
Dim pageCount As Integer = 0
Private Sub Form1_Load(...)
NextPicture()
End Sub
Private Sub Button1_Click(...)
NextPicture()
End Sub
Private Sub NextPicture()
Me.Picture1.Image = System.Drawing.Image.FromFile("C:\files\" & pageCount & ".bmp")
pageCount = pageCount + 1
End Sub
When the form loads, it calls the NextPicture() function which displays the first picture. Each time you click the button after that it will display the next picture. Of course, you'll want to add some error checking in there too so you don't try to open a file that doesn't exist. ;)
Re: Looping through each file in directory
At form load event, use DirectoryInfo and its function GetFiles(".bmp") to add all .bmp file names to an arrayList, then set your pointer to zero. Set your PicBox.Image to arrayList(pointer) which now is the first element in the arraylist.
In button click event, increase the pointer then set the picBox image again. Just make sure that the pointer doesn't out of bound. If it is, set it back to zero.
Re: Looping through each file in directory
Everyone seems determined to use DirectoryInfo and FileInfo objects all the time. There's no point if all you're using is the file and folder paths. Use the Directory and File classes instead, which have all Shared members and thus require no instances to be created. All you get are the String objects containing the paths, which is all you need:
VB Code:
Dim filePaths As String() = IO.Directory.GetFiles("folder path here", "*.bmp")
For Each filePath As String In filePaths
MessageBox.Show(filePath)
Next filePath