ARTICLE

OpenFileDialog in WPF using VB.NET

Posted by Mahesh Chand Articles | WPF using VB.NET September 26, 2009
This article shows how to create and use a Open FileDialog in WPF using Visual Basic .NET.
Download Files:
 
Reader Level:

The OpenFileDialog is used to browse files on a machine.

 

The OpenFileDialog class defined in Microsoft.Win32.OpenFileDialog namespace represents an OpenFileDialog control in WPF.

 

Let's add a TextBox and a Button control to a XAML page. The window looks like this.

OpenFileDialog.jpg

 

 

When you click the Browse button, we will browse text files and set the TextBox.Text to the selected file name.

 

<TextBox Height="32" HorizontalAlignment="Left" Margin="6,10,0,0" Name="FileNameTextBox"

                 VerticalAlignment="Top" Width="393" />

        <Button Content="Browse" Height="32" HorizontalAlignment="Left" Margin="405,10,0,0"

                Name="button1" VerticalAlignment="Top" Width="88" Click="button1_Click" />

 

The code listed in Listing 1 creates an OpenFileDialog, set its default extension and filter properties and calls ShowDialog method that displays the dialog. Once the OpenFileDialog is displayed, you can use it to browse files. Once file is selected, the FileName property of the OpenFileDialog is set to the selected file name. This code sets the selected file name as a TextBox.Text property.


Private Sub BrowseButton_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)

 

        ' Create OpenFileDialog

        Dim dlg As Microsoft.Win32.OpenFileDialog = New Microsoft.Win32.OpenFileDialog()

 

        ' Set filter for file extension and default file extension

        dlg.DefaultExt = ".doc"

        dlg.Filter = "Word documents (.doc)|*.doc"

 

        If (dlg.ShowDialog() = True) Then

            Dim fileName As String = dlg.FileName

            If (dlg.FileName.Length > 0) Then

                SelectedFileTextBox.Text = dlg.FileName

            End If

        End If

 

    End Sub


Download the attached project for more details.



Login to add your contents and source code to this article
share this article :
post comment
 
Team Foundation Server Hosting
Become a Sponsor
PREMIUM SPONSORS
  • ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
    The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
Nevron Diagram
Become a Sponsor