DialogResult with FolderBrowserDialog in WPF

 ̄綄美尐妖づ 提交于 2019-12-01 15:51:22

Okay so it turns out all answers other answers here were right.

They just missed out one thing and I think that was my fault...

Every time I saw DialogResult in Intellisense when trying to use it in my if statement (as I've been told to use, I saw this:

bool? Window.Dialog.Result
Gets or sets the dialog result value, which is the value that is returned from the
System.Windows.Window.ShowDialog() method.

Exceptions:
System.InvalidOperationException

This particular DialogResult object isn't the one I was looking for.

What finally worked was the following:

DialogResult result = fbd.ShowDialog();

if (result == System.Windows.Forms.DialogResult.OK)
{
    // do work here
}

It's worth noting that I do have System.Windows.Forms referenced in my usings which is why I never thought to reference the class from System as in the above snippet. I thought it was using this anyway.

DialogResult is an enumeration and defines values to indicate the return values of dialogs.

In your code you should check for DialogResult.OK to init your variable with the path selected in the dialog. DialogResult.OK is returned when the "OK"-Button is pressed in the dialog, otherwise is DialogResult.Cancel returned.

if (result == DialogResult.OK){
  txtSource.Text = fbd.SelectedPath;
}

Late answer here but why not just . .

private void SelectFolder()
{
    var dialog = new FolderBrowserDialog();
    var status = dialog.ShowDialog(); // ShowDialog() returns bool? (Nullable bool)
    if (status.Equals(true))
    {
        SelectedFolderPath = dialog.SelectedPath;
    }
}

You can see the result in debugging session. It returns false when the Cancel button is clicked.

DialogResult.(OK, Cancel whatever you want to check),

if (result == DialogResult.OK) // DialogResult.(Your desired result, select from the list it generates)
{
    txtSource.Text = fbd.SelectedPath;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!