HomeSearch

VB.NET OpenFileDialog Example

This VB.NET article uses the OpenFileDialog control in Windows Forms. It allows users to select files.
OpenFileDialog. Users often need to select files in a program. In Windows Forms, we use the OpenFileDialog control. And we can control and access properties of this control with VB.NET code. This prebuilt dialog makes development faster and easier.
ShowDialog. To start, please create a new Windows Forms project in Visual Studio. Open the Toolbox. Then add a Button control and an OpenFileDialog control. Double-click on the Button control to create a Button1_Click event handler.

Then: In the Button1_Click event handler, add a called to OpenFileDialog1.ShowDialog.

Tip: Assign a DialogResult Dim to the result of the ShowDialog Function. Then test the DialogResult with an If-Statement.

VB.NET program that uses OpenFileDialog, ShowDialog Public Class Form1 Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click ' Call ShowDialog. Dim result As DialogResult = OpenFileDialog1.ShowDialog() ' Test result. If result = Windows.Forms.DialogResult.OK Then ' Do something. End If End Sub End Class
When you execute this program, you will get a Windows Forms window with a Button on it. You can click the button and an OpenFileDialog, similar to the screenshot at the top, will appear.

And: When you close the OpenFileDialog, control flow returns to the Button1_Click event handler.

Read file. Next, we read a file the user selects in the OpenFileDialog. We detect the DialogResult.OK value—this occurs when the OK button is pressed. We then use File.ReadAllText to load in the text file.File.ReadAllText

Note: When the file is read, and the OK button is pressed, the length of the file is displayed in the title bar of the window.

VB.NET program that uses OpenFileDialog, reads file Imports System.IO Public Class Form1 Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click ' Call ShowDialog. Dim result As DialogResult = OpenFileDialog1.ShowDialog() ' Test result. If result = Windows.Forms.DialogResult.OK Then ' Get the file name. Dim path As String = OpenFileDialog1.FileName Try ' Read in text. Dim text As String = File.ReadAllText(path) ' For debugging. Me.Text = text.Length.ToString Catch ex As Exception ' Report an error. Me.Text = "Error" End Try End If End Sub End Class
Properties. The OpenFileDialog has many properties. We use these properties to perform many of the important tasks with this control. We use the FileName property to get the path selected by the user.Property
Summary. Windows Forms is a powerful toolkit. With it we can create a custom file dialog. But this is often not needed—the OpenFileDialog handles most common requirements. It has many features and properties.
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.
Home
Dot Net Perls