ako
ako

Reputation: 2126

folderBrowserDialog does not work in c#

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 .

Upvotes: 1

Views: 3432

Answers (4)

Naresh Bisht
Naresh Bisht

Reputation: 719

Add STAThread Attribute to the main method.

static class Program
{
    [STAThread]
    static void Main(string[] args)
    {
        ...        
    }
}

Upvotes: 3

ako
ako

Reputation: 2126

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

Upvotes: 0

Valeh Mikayilzadeh
Valeh Mikayilzadeh

Reputation: 919

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

Upvotes: 0

Sleepy Panda
Sleepy Panda

Reputation: 458

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

using (var dialog = new FolderBrowserDialog())
    if (dialog.ShowDialog() == DialogResult.OK)
    {
         // some code...
    }

Upvotes: 1

Related Questions