Dialog to browse for a file and sets the resulted file as the text box text. - CSharp System.Windows.Forms

CSharp examples for System.Windows.Forms:Dialog

Description

Dialog to browse for a file and sets the resulted file as the text box text.

Demo Code


using System.IO;//from www  . ja  v a2  s .  co m
using System.Windows.Forms;
using System;

public class Main{
            /// <summary>
            /// This method browses for a file and sets
            /// the resulted file as the text box text.
            /// </summary>
            /// <param name="textBox"></param>
            public static void ChooseFile(TextBox textBox, string filter = "", string selectedPath = "")
            {
                // open fileDialog
                OpenFileDialog fileBrowser = new OpenFileDialog();
                
                // if the filter exists
                if (TextHelper.Exists(filter))
                {
                    // Set the filter
                    fileBrowser.Filter = filter;
                }

                // if the selectedPath exists
                if (TextHelper.Exists(selectedPath))
                {
                    // set the directory to look in 
                    fileBrowser.InitialDirectory = selectedPath;
                }

                // Show fileBrowser
                fileBrowser.ShowDialog();

                // if the text box exists
                if (textBox != null)
                {
                    // Set text on text box
                    textBox.Text = fileBrowser.FileName;
                }
            }
}

Related Tutorials