Whenever you need to allow a user to open a particular file without forcing the user to type the full path and file name, you can use the OpenFileDialog class. OpenFileDialog has a number of properties and methods that make it a flexible way to get users to pick a file. In this tip, I present an example that shows how you can use OpenFileDialog in VB.NET.
Put OpenFileDialog to useIt's very easy to use the OpenFileDialog class, which you will find under the Dialogs section of the toolbox. To add the control to your form, double-click it, and the component will appear below the form as in Figure A. Figure A
For my example, I will also add a textbox and a command button to the form. To do so, change the text property of the command button to Open File and add the following code to the button's click event and to the FileOK event of the OpenFileDialog box:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.ClickPress [F5] to debug, and your form will look like Figure B. Figure B
OpenFileDialog1.Title = "Please Select a File"
OpenFileDialog1.InitialDirectory = "C:temp"
Private Sub OpenFileDialog1_FileOk(ByVal sender As System.Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles OpenFileDialog1.FileOk
Dim strm As System.IO.Stream
strm = OpenFileDialog1.OpenFile()
TextBox1.Text = OpenFileDialog1.FileName.ToString()
If Not (strm Is Nothing) Then
'insert code to read the file data
End IfEnd Sub
Click the Command button to open the File Open dialog box, as in Figure C. Figure C
Once you select the file and click Open, the dialog box closes, and the full path of the file appears with the file name in the textbox. See Figure D. Figure D
Notes about the example
I begin by setting the Title property of the OpenFileDialog box. Then, I set the initial directory that will open the first time the dialog box opens up. (The user can change it to any directory in run time.) I open the OpenFileDialog1 by using its ShowDialog method. After the user selects the file, I set the Text property of the textbox control to the file name selected in the OpenFileDialog with the help of the OpenFileDialog's FileName property. I open the file that the user selected and then close it.
You can use the functionality provided here to open the selected file or to store the name of the file that was selected, depending on the purpose of your particular application.
Irina Medvinskaya has been involved in technology since 1996. She has an MBA from Pace University and works as a project manager at Citigroup.
————————————————————————————————————————————Get Visual Basic tips in your inbox
Advance your scripting skills to the next level with TechRepublic's free Visual Basic newsletter, delivered each Friday. Automatically subscribe today!