Reputation: 75
Good morning,
I'm trying to figure out how to properly use the OpenFileDialog function in C# to allow a user to select a desired output folder. Right now I have a button and a textbox on my windows form. The user would hit the button, and that would open up the dialog GUI at run-time to allow the user to navigate to the the output location, then hit ok. Then they should have the confirmation of their selection by having the path displayed in the textbox.
The code I have right now is as follows:
private void button1_Click_3(object sender, EventArgs e)
{
OpenFileDialog OutputFilePath = new OpenFileDialog();
string OutputString = OutputFilePath.FileName;
FilePathBox.Text = OutputString;
}
It compiles just fine, but when I hit the button, it doesn't bring up the file dialog box.
I'm sure it's something simple that I'm not seeing?
Thanks in advance!
~Andrew
Upvotes: 0
Views: 1416
Reputation: 2292
You need to use ShowDialog()
private void button1_Click_3(object sender, EventArgs e)
{
using(OpenFileDialog OutputFilePath = new OpenFileDialog())
{
if(OutputFilePath.ShowDialog() == DialogResult.OK)
{
string OutputString = OutputFilePath.FileName;
FilePathBox.Text = OutputString;
}
}
}
Wrapping the dialog in a using
clause will ensure the form is garbage collected.
Upvotes: 2
Reputation: 35720
you need to show Dialog and then check DialogResult because user can click Cancel
OpenFileDialog OutputFilePath = new OpenFileDialog();
var res = OutputFilePath.ShowDialog();
if (res == DialogResult.OK)
{
string OutputString = OutputFilePath.FileName;
FilePathBox.Text = OutputString;
}
Upvotes: 4