1

when i click on the button to select a folder using folderBrowserDialog in c# the dialog is not shown and the result of dialog is set to Cancel automatically ..here is the code behind Button_Click :

private void glassButton1_Click(object sender, EventArgs e)
{
    DialogResult result = folderBrowserDialog1.ShowDialog();//here Dialog is not shown and result=Cancel
    if (result==DialogResult.OK)
    {
        folderBrowserDialog1.ShowNewFolderButton = true;
        backupPath = folderBrowserDialog1.SelectedPath.ToString();
        if (Directory.Exists(backupPath))
            backupTextBox.Text = backupPath;
        //else MessageBox.Show("path is invalid", "error", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
    }
}

how can i fix it ? thanks .

Grant Winney
  • 65,241
  • 13
  • 115
  • 165
ako
  • 2,000
  • 2
  • 28
  • 34

4 Answers4

3

Add STAThread Attribute to the main method.

static class Program
{
    [STAThread]
    static void Main(string[] args)
    {
        ...        
    }
}
Naresh Bisht
  • 645
  • 6
  • 16
1

Here's the code, it works fine for me.

using (var dialog = new FolderBrowserDialog())
    if (dialog.ShowDialog() == DialogResult.OK)
    {
         // some code...
    }
Sleepy Panda
  • 458
  • 3
  • 9
0

You code works correctly. result is DialogResult.OK when you click FolderBrowserDialog "OK Button". if you click "cancel" or "close" button when result value setting is DialogResult.Cancel

0

from project properties -> build section -> platform target , i checked Prefer 32-bit checkBox and it solved my problem .

ako
  • 2,000
  • 2
  • 28
  • 34
  • i think the problem is someways related to the **COM** components , as folderBrowserDialog is a component from COM technology, but i don't know what the problem was with that . – ako Aug 20 '16 at 12:23