How to check whether files are selected?

private void BrowseFilesButton_Click(object sender, RoutedEventArgs e) { var ofd = new OpenFileDialog {Multiselect = true}; ofd.ShowDialog(); ViewModel.ChoosenFiles = ofd.FileNames; FileBox.Text = $"Selected {ofd.FileNames.Length} scripts"; } private void ExecFilesButton_Click(object sender, RoutedEventArgs e) { List<Script> scriptToRun = ViewModel.ChoosenFiles.Select(item => new Script(item)).ToList(); SetProgressBar(scriptToRun.Count); var runner = new Runner(ViewModel.SelectedConnection); runner.RunQueries(scriptToRun, UpdateProgressBar()); MessageBox.Show("ok"); } 
  • obviously ofd.FileNames.Any () - free_ze

3 answers 3

You need to check how the user closed the dialogue: using OK or in some other way.

To do this, use the design

 if (ofd.ShowDialog() == true) ... 

(comparison with true necessary because the return type is bool? and not bool ).

A value of true means that the dialog is closed with the OK button, in this case the file list must be non-empty.

In the case of other return values ​​( false or null ) the dialog was closed with another button ( Esc , Cancel, Alt + F4 , ...), and there are no selected files. (The current implementation never seems to return null .)

     private void BrowseFilesButton_Click(object sender, RoutedEventArgs e) { using (var ofd = new OpenFileDialog {Multiselect = true}) { System.Windows.Forms.DialogResult result = ofd.ShowDialog(); if (result != DialogResult.OK || ofd.FileNames.Length == 0) return; ViewModel.ChoosenFiles = ofd.FileNames; FileBox.Text = $"Selected {ofd.FileNames.Length} scripts"; } } 
    • DialogResult.OK - wpf swears - YoFi
    • Completed the answer by specifying the fully-qualified type name for DialogResult. Using DialogResult instead of bool? gives a much more flexible logic control. - Anton Papin

    I did it like this:

     private void BrowseFilesButton_Click(object sender, RoutedEventArgs e) { var ofd = new OpenFileDialog{Multiselect = true}; ofd.ShowDialog(); if (ofd.FileNames.Length == 0) return; ViewModel.ChoosenFiles = ofd.FileNames; FileBox.Text = $"Selected {ofd.FileNames.Length} scripts"; } private void ExecFilesButton_Click(object sender, RoutedEventArgs e) { if(ViewModel.ChoosenFiles.Length == 0) { MessageBox.Show("Choose sql files"); } else { List<Script> scriptToRun = ViewModel.ChoosenFiles.Select(item => new Script(item)).ToList(); SetProgressBar(scriptToRun.Count); var runner = new Runner(ViewModel.SelectedConnection); runner.RunQueries(scriptToRun, UpdateProgressBar()); MessageBox.Show("ok"); } }