views:

25

answers:

2

In my Windows Form's Form_Load event, I want to show a FolderBrowserDialog to let the user select a directory, and if the directory they've selected is not valid (meaning it lacks certain files that the application needs), I want to show it again. However, when I create a new FolderBrowserDialog, it does not appear when I call ShowDialog.

while (ValidDirectorySelected() == false && tryAgain == true)
{
 using (FolderBrowserDialog dialog = new FolderBrowserDialog())
 {
  dialog.ShowNewFolderButton = false;

  if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.Cancel)
  {
   tryAgain = false;
  }
 }
}

When I step into it, the dialog.ShowDialog() line is reached on the second time, and then nothing happens. The dialog does not appear, and the debugger doesn't move on. It just stops. It works perfectly the first time, but not the second. I've even tried just copying that entire using block and pasting it right after the first one, and the same thing happens. The dialog shows only once.

What do I need to do to show a FolderBrowserDialog more than once?

Solution:

Passing 'this' to ShowDialog fixed my issue. I also moved the using to outside of the while loop, to avoid needlessly re-creating the dialog.

+1  A: 

Try this:

using (FolderBrowserDialog dialog = new FolderBrowserDialog())
{
    while (ValidDirectorySelected() == false && tryAgain == true)
    {
        dialog.ShowNewFolderButton = false;

        if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.Cancel)
        {
            tryAgain = false;
        }
    }
}

...move your using outside the while loop to keep from destroying the folder browser every time. You don't have to do that. You can reuse FolderBrowserDialog.

Paul Sasik
+2  A: 

Minimize Visual Studio, you'll find the dialog back.

This is a focus issue, triggered because you display the dialog in the Load event. When the dialog closes, there is no window left in your app that can receive the focus. Your Load event hasn't finished running so the app's main window isn't yet visible. Windows has to find a window to give the focus to and will select one from another program. Like Visual Studio.

When you display the dialog again, it cannot steal the focus back because Visual Studio has acquired it. So the dialog appears behind Visual Studio's main window, out of view.

You'll have to fix this by allowing your main window to become visible. And call dialog.ShowDialog(this) to be completely sure. You could use the Shown event, for example.

Hans Passant
Simply passing 'this' to ShowDialog fixed the issue. Thank you.
Mike Pateras