Home
VB.NET.WinForms
OpenFileDialog Example
This page was last reviewed on Sep 22, 2022.
Dot Net Perls
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.
Some notes. 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.
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.
Result When you execute this program, click the button. An 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
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.
Note We then use File.ReadAllText to load in the text file. This performs the actual file loading.
Finally When the OK button is pressed, the length of the file is displayed in the title bar of the window.
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. 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 summary. A custom file dialog is rarely needed—the OpenFileDialog handles most common requirements. It has many features and properties.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Sep 22, 2022 (rewrite).
Home
Changes
© 2007-2024 Sam Allen.