This tutorial follows on from the previous section
In the previous section, we saw how to add an Open File Dialogue to our menus. We then saw how to add an Initial Directory and a Title property. In this section, we'll learn about the Filter property.
The Filter Property
In most dialogue boxes, you can display a list of specific files that can be opened. These are displayed in the "Files of Type" drop down list. To do this in VB.NET, you access the Filter property. We'll restrict our users to only opening Text files, those that end in the extension ".txt".
The following code shows how to use the filter property:
openFD.InitialDirectory = "C:\"
openFD.Title = "Open a Text File"
openFD.Filter = "Text Files|*.txt"
Run your code. Click File > Open on your menu, and then click the arrow on the drop down box for "Files of Type". You should see this:
If you examine yourOpen dialogue box, you should see only text files displayed (you'll still see folders). If you can't see any files at all, double click a folder and explore. You'll soon see something like this:
To display files of more than one type, add a Pipe character between each filter. In the code below, two file types are specified, text files and Microsoft Word documents:
openFD.Filter = "Text Files|*.txt|Word Files|*.doc"
When the programme is run, you should be able to see two file types in the list:
If you want to launch the Open File Dialog Box inside of your Documents folder, there is some special code for this (it's a bit for this page, though, and should be on one line):
openFD.InitialDirectory = Environment.GetFolderPath( Environment.SpecialFolder.MyDocuments )
After the equal sign, you need Environment.GetFolderPath. In between round brackets, you can then specify a folder with Environment.SpecialFolder. As soon as you type a dot after SpecialFolder you'll see a menu appear. This one:
These folders are ones that have already been set up on your computer by Microsoft.
Select the special folder that you want as your initial directory. The Documents
folder is actually called MyDocuments.
In the next section, we'll see how to return which file was selected by the user.