Search code examples
c#textboxfilepathopenfiledialog

Beginners help C# showing a filepath in text box


I'm new to programming and am using C# and Visual Studio Express 2012. I am creating a windows form and have inserted a button which runs open file dialog when clicked. I have a text box on the form that I'd like to have show the file path of the file that the user selected. I have found some code examples on this site but struggle to understand where they should be placed in the code structure as the examples are often standalone snippets. I hope its not too dumb a question!

Thanks in advance

Lee

The answer in case it's of use to anyone was.......

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        using (FileDialog fileDialog = new OpenFileDialog())
        {
            if (DialogResult.OK == fileDialog.ShowDialog())
            {
                string filename = fileDialog.FileName;

                textBox1.Text = fileDialog.FileName;
            }
        }
    }
}

Solution

  • Your OpenFileDialog has property FileName that contains the path of the selected file, assign that to your TextBox.Text

    if (openFileDialog.ShowDialog() == DialogResult.OK)
    {
        yourTextBox.Text = openFileDialog.FileName;            
    }