OpenFileDialog in Visual Basic .NET
Tags: VB.NET, VB 2008, VB 2010, VB 2012, VB 2013
This lesson describes the OpenFileDialog control
Visual Basic offers a wide range of dialog boxes that allow the user to make standard selections and each of them has a very specific purpose.
The purpose of the OpenFileDialog is selecting a file to open.
To display a file selection dialog, this component calls its ShowDialog method, which returns DialogResult.OK if the user selects a file and clicks OK, and DialogResult.Cancel if the user cancels.
This component provides a lot of properties for determining what kind of files the user can select.
For example, using the Filter property you can limit the user search for only images with extension .jpg and .png
OpenFileDialog1.Filter = "Jpeg Files (*.jpg)|*.jpg|Png Files (*.png)|*.png"
To get the file name selected in the file dialog box, you use its FileName property
Private Sub BrowseButton_Click(sender As Object, e As EventArgs) Handles BrowseButton.Click If OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then SelectedFile.Text = OpenFileDialog1.FileName End If End Sub
One more useful property is the MultiSelect property which determines whether the user can select multiple files, and if so you get the selected files as following:
Private Sub BrowseButton_Click(sender As Object, e As EventArgs) Handles BrowseButton.Click If OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then For Each file As String In OpenFileDialog1.FileNames MessageBox.Show(file) Next End If End SubPrevious Lesson | Next Lesson