Reputation:
This seems so simple, but I have been trying to get this to work properly, but I just can't. Here is the original code:
ofd = new OpenFileDialog();
if (ofd.ShowDialog() == DialogResult.OK)
{
mFileName = ofd.FileName;
}
Problem is, if the user hits the cancel button on the dialog box, then a bunch of my other code continues to execute, such as opening the database connection and such, which is unnecessary since the user selected cancel. So I then tried:
if (ofd.ShowDialog() == DialogResult.Cancel)
{
return;
}
else if (ofd.ShowDialog() == DialogResult.OK)
{
mFileName = ofd.FileName;
}
While this prevents the problem before, another arises. If the user selects cancel, it stops. But then it will open a second dialog box, which it shouldn't.
I can't seem to only open one dialog box, if the user hits cancel return, else if the user hits open, then it continues. Thanks.
Upvotes: 1
Views: 111
Reputation: 78595
The problem here is that you are calling ShowDialog()
multiple times. It returns a DialogResult enum so you can store it in a variable the like this:
DialogResult result = ofd.ShowDialog();
Then you can work on it multiple times without having to show the dialog again:
if(result == DialogResult.OK) {
// OK!
}
else if(result == DialogResult.Cancel) {
return; // Exit function
}
else {
// Anything else you need to do
}
Upvotes: 1