OpenFileDialog
Users often need to select files in a program. In Windows Forms, we use the OpenFileDialog
control. We access properties of this control with VB.NET.
This dialog makes development faster and easier. In most situations, it makes no sense to use a different way to select files from a UI.
To start, please create a new Windows Forms project in Visual Studio. Add a Button
and an OpenFileDialog
. Double
-click on the Button
to create a click event handler.
Button1_Click
event handler, add a called to OpenFileDialog1.ShowDialog
.DialogResult
Dim
to the result of the ShowDialog
Function. Then test the DialogResult
with an If
-Statement.OpenFileDialog
, similar to the screenshot, will appear.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
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.
File.ReadAllText
to load in the text file. This performs the actual file loading.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
We use properties to perform many of the important tasks with OpenFileDialog
. We use the FileName
property to get the path selected by the user.
A custom file dialog is rarely needed—the OpenFileDialog
handles most common requirements. It has many features and properties.