Friday, February 25, 2011

How to use OpenFileDialog in WPF


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.








When you click the Browse button, we will browse text files and set the TextBox.Text to the selected file name.
 
<TextBox Height="25" HorizontalAlignment="Left" Margin="41,104,0,0" Name="txtFileUpload" VerticalAlignment="Top" Width="405" Grid.RowSpan="2" />

<Button Content="Browse" Height="26" HorizontalAlignment="Left" Margin="448,103,0,0" Name="btnBrowse" VerticalAlignment="Top" Width="75" Click="btnBrowse_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 void btnBrowse_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog fdlg = new OpenFileDialog();
            fdlg.Title = "File Upload";
            fdlg.Filter = "Xml File|*.xml";
            //fdlg.FilterIndex = 2;
            fdlg.RestoreDirectory = true;
            Nullable<bool> result = fdlg.ShowDialog();
            if (result==true)
            {
                txtFileUpload.Text = fdlg.FileName;
            }
        }


No comments:

Post a Comment