Dialog to choose a folder. - CSharp System.Windows.Forms

CSharp examples for System.Windows.Forms:Dialog

Description

Dialog to choose a folder.

Demo Code


using System.IO;//from   w w  w.  j a  v  a2  s.  c o  m
using System.Windows.Forms;
using System;

public class Main{
        #endregion

            #region ChooseFolder(TextBox textBox, string selectedPath)
            /// <summary>
            /// This method is used to choose a folder.
            /// </summary>
            /// <param name="textBox"></param>
            /// <returns></returns>
            public static void ChooseFolder(TextBox textBox, string selectedPath)
            {
                // Create folderBrowser
                FolderBrowserDialog folderBrowser = new FolderBrowserDialog();

                // Set the selectedPath
                folderBrowser.SelectedPath = selectedPath;
                
                // Show folderbrowser
                folderBrowser.ShowDialog();

                // if there is a selectedPath
                bool hasSelectedPath = (!String.IsNullOrEmpty(folderBrowser.SelectedPath));
                bool hasTextBox = (textBox != null);

                // if the text box exists
                if ((hasSelectedPath) && (hasTextBox))
                {
                    // Set text on text box
                    textBox.Text = folderBrowser.SelectedPath;
                }
            }
        #region Static Methods

            #region ChooseFolder(TextBox textBox)
            /// <summary>
            /// This method makes it easy to select a path and display it in a TextBox
            /// </summary>
            /// <param name="textBox"></param>
            /// <returns></returns>
            public static void ChooseFolder(TextBox textBox)
            {
                // Create folderBrowser
                FolderBrowserDialog folderBrowser = new FolderBrowserDialog();
                
                // Show folderbrowser
                folderBrowser.ShowDialog();
                
                // if the text box exists
                if(textBox != null)
                {
                    // Set text on text box
                    textBox.Text = folderBrowser.SelectedPath;
                }
            }
}

Related Tutorials