Recipe 12.14. Browsing for a Directory


The user needs to specify a directory on the file system in which files should be stored or accessed, and you want it to be done graphically, not just through a textentry field.


Sample code folder: Chapter 12\DirectoryLocator

Use a FolderBrowserDialog control to display the standard Windows directory-browsing tool.


Create a new Windows Forms application, and add a TextBox control named TargetDirectory, a Button control named LookForDirectory, and a FolderBrowserDialog control named DirectoryBrowser. (You'll find the FolderBrowserDialog control in the Dialogs area of the Visual Studio Toolbox.) Change the Text property of the button to Browse…. Adding an informative label gives you the form in Figure 12-10.

Add the following source code to the form's class template:

 Private Sub LookForDirectory_Click( _       ByVal sender As System.Object, _       ByVal e As System.EventArgs) _       Handles LookForDirectory.Click    ' ----- Locate a directory graphically.    DirectoryBrowser.Description = _ 

Figure 12-10. Controls for the directory-browsing sample

       "Which directory do you want to use?"    If (DirectoryBrowser.ShowDialog( ) = _          Windows.Forms.DialogResult.OK) Then       TargetDirectory.Text = DirectoryBrowser.SelectedPath    End If End Sub 

To use the program, click on the Browse button, and use the resulting dialog (shown in Figure 12-11) to select a directory.

Figure 12-11. The standard directory browser dialog

The FolderBrowserDialog class represents one of several system-supplied dialogs made available to your Visual Basic applications. Other related dialogs let you browse for files (OpenFileDialog and SaveFileDialog), select fonts (FontDialog), and choose colors (ColorDialog). There are also several printer-specific dialogs. (See Chapter 11 for related recipes.)

Despite their different purposes, all the dialog controls are used in a similar way:

  1. Add the dialog control to your form, or create an instance of it as a variable.

  2. Set any relevant properties, as is done with the Description property in this recipe.

  3. Display the dialog to the user with the ShowDialog( ) method.

  4. If the user makes a selection and clicks the OK button, the dialog returns System.Windows.Forms.DialogResult.OK. If the user cancels, the dialog returns System.Windows.Forms.DialogResult.Cancel.

  5. Examine the properties of the control for user-modified settings.

Visual Basic 2005 Cookbook(c) Solutions for VB 2005 Programmers
Visual Basic 2005 Cookbook: Solutions for VB 2005 Programmers (Cookbooks (OReilly))
ISBN: 0596101775
EAN: 2147483647
Year: 2006
Pages: 400

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: