Fill a List Box with a List of Files

Problem

You need to present your users with a sorted list of files with a specific filename extension in a particular directory. You found the Dir function, but you can’t find a way to get this information into a list box. Is there a way to do this?

Solution

This problem provides the perfect opportunity to use the past three solutions. It involves creating a list-filling callback function, passing arrays as parameters, and sorting an array. In addition, you’ll fill that array with a list of files matching a particular criterion, using the Dir function.

Load the form frmTestFillDirList from 07-08.MDB. Enter a file specification into the text box (for example, c:\windows\*.ini). Once you leave the text box (by pressing either Tab or Return), the code attached to the AfterUpdate event will force the list box to requery. When that happens, the list box will fill in with the matching filenames. Figure 7-12 shows the results of a search for c:\winnt\*.exe.

frmTestFillDirList, searching for *.exe in the Windows directory

Figure 7-12. frmTestFillDirList, searching for *.exe in the Windows directory

To include this functionality in your own applications, follow these steps:

  1. On a form, create a text box and a list box, with properties set as shown in Table 7-6.

    Table 7-6. Property settings for the controls on the directory list form

    Control

    Property

    Setting

    Text box

    Name

    txtFileSpec

    AfterUpdate

    [Event Procedure] ...

Get Access Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.