Quantcast
Channel: Windows Forms General forum
Viewing all articles
Browse latest Browse all 12583

OpenFileDialog Browse to TextBox Value

$
0
0

I am trying to create a Windows Forms application with a text box to enter a filename and and associated Browse button, so the user can select a file.

Clicking the Browse button will display an OpenFileDialog. When the user selects a file from that dialog, the text on the TextBox is updated to the path and filename selected. I want the dialog to initially browse to the path/filename in the TextBox when the dialog shows up. For instance, if the value of the TextBox is 'c:\Temp\MyFile.txt', I want the OpenFileDialog to open in the Temp directory, with 'MyFile.txt' entered as the filename.

This is the code for my browse button:

private void btnBrowse_Click(object sender, EventArgs e)
{
    //Set initial file for Browse dialog to text value.
    ofdBrowse.FileName = txtControlFile.Text;

    if (ofdBrowse.ShowDialog() == DialogResult.OK)
    {
        //If OK, update the text box.
        txtControlFile.Text = ofdBrowse.Filename;
    }
}

Unfortunately, this isn't working like I want. Whenever I click the Browse button, the OpenFileDialog always starts in the directory it was in the last time I used the dialog, even if the path of the file in the text is different. The text box on the open dialog displays the complete path and filename from the TextBox, instead of just the filename.

Being a VB6 programmer, I've used similar code with a CommonDialog control's open dialog, and it behaves the way I want it.

What would be the best way to make an OpenFileDialog initialize at a full path and filename?


Viewing all articles
Browse latest Browse all 12583

Trending Articles