C# Folder Browser Dialog with TextBox [Complete Example]

In this C# tutorial, I will show you how to use the Folder Browser Dialog with a TextBox in C# Windows Forms applications. By the end of this guide, you’ll know how to let users select folders through a Folder Browser Dialog and display the selected folder path in a TextBox.

C# Folder Browser Dialog with TextBox

In Windows Forms applications, the FolderBrowserDialog component provides an interface to browse and select folders. It’s often useful to combine it with a TextBox control to show the selected folder path.

Follow the below steps:

1. First, I have created a Windows forms application (C#). Then, I added a Textbox and a button control to the interface. We will use the button to trigger the Folder Browser Dialog and the textbox to display the selected folder path.

For this, drag and drop a textbox and button to the interface, and the form looks like the one below. Make sure to follow the control naming conventions.

c# folder browser dialog with text box

2. Then, double-click on the button that will generate the event handler where you can write the code. In this event handler, add the following code to show the Folder Browser Dialog and get the selected path.

namespace DotNetDemo
{
    using System.Windows.Forms;
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnBrowseFolder_Click(object sender, EventArgs e)
        {
            using (FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog())
            {
                DialogResult result = folderBrowserDialog.ShowDialog();
                if (result == DialogResult.OK)
                {
                    txtFolderPath.Text = folderBrowserDialog.SelectedPath;
                }
            }
        }
    }
}

In the above code, we’re:

  • Instantiating a FolderBrowserDialog object.
  • Displaying the dialog with the ShowDialog() method.
  • Checking if the user clicked “OK” in the dialog.
  • If so, setting the TextBox text to the selected folder path.

3. Now, click on F5 to run the Windows form application. Click the btnBrowseFolder button. The Folder Browser Dialog will appear. Select a folder and click “OK”. The selected folder path will be displayed in the txtFolderPath TextBox.

c# folder browser dialog with text box example

Conclusion

By following the above steps and code, you can implement a Folder Browser Dialog with a TextBox in a C# Windows Forms application. This is how to use Folder Browser Dialog with TextBox in C#.

You may also like: