Jul 19, 2011

Directory Selection in Windows Forms using C#.Net


Add the FolderBrowser Dialog to the form from the Dialogs Collection (see below).











This control will not be placed on the form but on a separate tray at the bottom of the Windows Forms Designer. (see below)













Now in the click event for the Button have the following code:




private void button5_Click(object sender, EventArgs e)
        {
            

            System.Windows.Forms.FolderBrowserDialog MyFolderBrowser = new System.Windows.Forms.FolderBrowserDialog();

            // Descriptive text displayed above the tree view control in the dialog box
            MyFolderBrowser.Description = "Select the Folder";

            // Sets the root folder where the browsing starts from
            //MyFolderBrowser.RootFolder = Environment.SpecialFolder.MyDocuments

            // Do not show the button for new folder
            MyFolderBrowser.ShowNewFolderButton = false;

            DialogResult dlgResult = MyFolderBrowser.ShowDialog();


            if (dlgResult == DialogResult.OK)
            {
  MessageBox.Show("You selected the file: " + MyFolderBrowser.SelectedPath);
            }
            else
            {
                MessageBox.Show("You hit cancel or closed the dialog.");
            }



        }



The FolderBrowserDialog component is displayed at run time using the ShowDialog method. Set the RootFolder property to determine the top-most folder and any subfolders that will appear within the tree view of the dialog box. Once the dialog box has been shown, you can use the SelectedPath property to get the path of the folder that was selected

the out put is 











No comments:

Post a Comment