Limit OpenFileDialog's Multiselect

2020-04-21 06:07发布

I have a OpenFileDialog and its MultiSelect property is ON. My question is how can I limit the number of items to be selected, for example 5 items only?

Thanks

3条回答
【Aperson】
2楼-- · 2020-04-21 06:31

You can use the FileOk event to check the file(s) selected by the user when he clicks the OK button. If you are not happy then display a message and set the CancelEventArgs.Cancel property to True to prevent the dialog from closing. Like this:

    Dim dlg As New OpenFileDialog()
    dlg.Multiselect = True
    AddHandler dlg.FileOk, Sub(s, ce)
                               If dlg.FileNames.Length > 5 Then
                                   MessageBox.Show("Please select no more than 5 files")
                                   ce.Cancel = True
                               End If
                           End Sub
    If dlg.ShowDialog = Windows.Forms.DialogResult.OK Then
        '' etc...
    End If
查看更多
冷血范
3楼-- · 2020-04-21 06:41

There is no built-in feature for that in OpenFileDialog as far as I can see. Possible solution is to check FileNames returned from the dialog. If it count more than 5, for example, alert user and stop without operating the files.

查看更多
▲ chillily
4楼-- · 2020-04-21 06:47

You cannot. But you have alternatives:

1.- A good alternative could be to put all file names in a text file, and then accept that text file as your program's input.

2.- You should allow user to pick the directory. Then you list all the files and let them select as many files, there will not be any problem.

3.- You may have to use a FolderBrowserDialog instead and then use IO.Directory.GetFiles, which works properly.

查看更多
登录 后发表回答