Let the user select a folder in C#

This example demonstrates two handy techniques. First, when you click this program's ellipsis button, the following code displays a FolderBrowserDialog. This lets the user pick a directory instead of needing to type it in.
// Display the folder browser dialog.
private void btnPickDirectory_Click(object sender, EventArgs e)
{
fbdDirectory.SelectedPath = txtDirectory.Text;
if (fbdDirectory.ShowDialog() == DialogResult.OK)
{
txtDirectory.Text = fbdDirectory.SelectedPath;
}
}

The code initializes the dialog to the directory path in the text box. (If this is not a valid path, the dialog defaults to its directory hierarchy root, in this case the Desktop. You can change the root by setting the dialog's RootFolder property at design time.)

The second useful technique is that the program saves the user's selection between runs. At design time I created a setting named Directory. When it starts, the program uses the following code to load the value saved in this setting.

// Restore the saved directory.
private void Form1_Load(object sender, EventArgs e)
{
txtDirectory.Text = Properties.Settings.Default.Directory;
}

The program uses the following code to save the current selection when the form closes.

// Save the current directory.
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
Properties.Settings.Default.Directory = txtDirectory.Text;
Properties.Settings.Default.Save();
}

  

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments
  • No comments exist for this post.
Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.