简体   繁体   English

Form.ShowDialog 方法

[英]Form.ShowDialog Methode

I have created a software, which save some Information in an Excel File.我创建了一个软件,它将一些信息保存在 Excel 文件中。 The software has two possibilities:该软件有两种可能性:

  1. To select the folder and then the software will create an Excel File with random name and there will save the data, or到 select 文件夹,然后软件将创建一个随机名称的 Excel 文件并保存数据,或

  2. To select an existed Excel File which is created from the user and there will save the data.到 select 一个现有的 Excel 文件,该文件由用户创建,将保存数据。

How to create a ONE ShowDialog to ask the user do you want to choose the folder or the file?!如何创建一个ONE ShowDialog来询问用户您要选择文件夹还是文件?!

Code that I have used to choose a Folder:我用来选择文件夹的代码:

using (var fbd = new FolderBrowserDialog())
           {
               DialogResult result = fbd.ShowDialog();

               if (result == DialogResult.OK && !string.IsNullOrWhiteSpace(fbd.SelectedPath))
               {

                   textBox3.Text = fbd.SelectedPath;

               }
          }

Code that I have used to choose a File:我用来选择文件的代码:

OpenFileDialog excelFilename = new OpenFileDialog();

           if (excelFilename.ShowDialog() == DialogResult.OK)
           {
               textBox3.Text = excelFilename.FileName;

           }

Maybe something like this?:也许是这样的?:

MessageBoxResult result = MessageBox.Show("Ask user what he wants to do", "", MessageBoxButton.YesNo);

string path = null;

//MessageBoxResult.Yes means File, .No means Folder
if (result == MessageBoxResult.Yes)
{
    //File-Picker
    OpenFileDialog filePicker = new OpenFileDialog()
    {
        FileName = "Excel File",
        DefaultExt = ".xls",
        Filter = "Excel Document | *.xls"
    };

    if (filePicker.ShowDialog() == true) 
    {
        path = filePicker.FileName;
    }
}
else if (result == MessageBoxResult.No)
{
    //Folder-Picker
    CommonOpenFileDialog folderPicker = new CommonOpenFileDialog()
    {
        IsFolderPicker = true,
        Multiselect = false
    };

    path = Path.Combine(folderPicker.FileName, DateTime.Now.ToString("yyyy-MM-ddTHH-mm-ss"));
    
    //Create file in folder
    File.Create(path);
}

if (path != null)
{
    // Do something with path (file user selected/program created)
}

Make sure you have the using System.Windows , using Microsoft.Win32;确保你有using System.Windowsusing Microsoft.Win32; and using System.IO;using System.IO; using's at the beginning of your program.在程序开始时使用。

You also have to add the WindowsAPICodePack library to your project to use the folder-picker.您还必须将WindowsAPICodePack库添加到您的项目中才能使用文件夹选择器。 You can do that with the NuGet manager.您可以使用 NuGet 管理器来做到这一点。 Here's the link to the library: WindowsAPICodePack - 1.1.1这是库的链接: WindowsAPICodePack - 1.1.1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM