views:

121

answers:

1

I have created an application compiled with .NET 3.5. and used the FolderBrowserDialog object. When a button is pressed i execute this code:

FolderBrowserDialog fbd = new FolderBrowserDialog (); fbd.ShowDialog();

A Folder dialog is showed but i can't see any folders. The only thing i see are the buttons OK & Cancel (and create new folder button when the ShowNewFolderButton properyty is set to true). When i try the exact same code on a different form everything is working fine. Any ideas??

A: 

Check that the thread running your dialog is on an STAThread. So for example make sure your Main method is marked with the [STAThread] attribute:

[STAThread]
static void Main() {
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);
    Application.Run(new Form1());
}

Otherwise you can do this (from the Community Content on FolderBrowserDialog Class):

/// <summary>
/// Gets the folder in Sta Thread
/// </summary>
/// <returns>The path to the selected folder or (if nothing selected) the empty value</returns>
private static string ChooseFolderHelper()
{
    var result = new StringBuilder();
    var thread = new Thread(obj =>
    {
        var builder = (StringBuilder)obj;
        using (var dialog = new FolderBrowserDialog())
        {
            dialog.Description = SpecifyDirectory;
            dialog.RootFolder = Environment.SpecialFolder.MyComputer;
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                builder.Append(dialog.SelectedPath);
            }
         }
     });

     thread.SetApartmentState(ApartmentState.STA);
     thread.Start(result);

     while (thread.IsAlive)
     {
         Thread.Sleep(100);
      }

    return result.ToString();
}
Jay Riggs