1

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 Answers 3

4

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 
Sign up to request clarification or add additional context in comments.

4 Comments

I have a problem with this. If I selected only 5 photos, the messagebox is still popping up. If i selected only 1 photo, the messagebox still shows
You must be doing it wrong, no idea what. Use the debugger, look at the value of dlg.FileNames
where can I find the debugger? Sorry, but I'm new to VB
I already got it. I used Filename instead of Filenames sorry for that.
1

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.

Comments

1

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.