我需要:单击按钮时打开“文件”对话框,然后选择多个文件,然后单击“确定”,然后这些文件将出现在Checkedlistbox1上。我希望对话框记住我上次浏览的文件夹路径(所以当我再次单击该按钮时,它将带我到那个位置)。但是,当我只运行"openfiledialog“时,我无法选择多个文件,而且当我添加进一步的代码时,程序会出现错误。请在这里亮点光。:)
Dim fbd As New OpenFileDialog With { _
.Title = "Select multiple files", _
.FileName = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory)}
If fbd.ShowDialog = DialogResult.OK Then
CheckedListBox1.Items.AddRange(Array.ConvertAll(IO.Directory.GetFiles(fbd.FileNames), Function(f) IO.Path.GetFileName(f)))
End If
发布于 2015-08-29 17:06:30
我在测试中使用了(字符串)列表,您可以更改它以满足您的需要。
Dim fbd As New OpenFileDialog With { _
.Title = "Select multiple files", _
.Multiselect = True, _
.FileName = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory)}
If fbd.ShowDialog = DialogResult.OK Then
CheckedListBox1.AddRange(fbd.FileNames.Select(Function(f) IO.Path.GetFileName(f)))
End If
编辑
我编辑了我的代码以便使用一个对象。下面是一个例子。您可以使用它创建CheckBoxList所需的对象。
Public Property CheckedListBox1 As New List(Of TestClass)
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim fbd As New OpenFileDialog With { _
.Title = "Select multiple files", _
.Multiselect = True, _
.FileName = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory)}
If fbd.ShowDialog = DialogResult.OK Then
CheckedListBox1.AddRange(fbd.FileNames.Select(Function(f) New TestClass With {.Name = IO.Path.GetFileName(f)}))
End If
End Sub
Public Class TestClass
Public Property Name As String
End Class
编辑2
Dim fbd As New OpenFileDialog With { _
.Title = "Select multiple files", _
.Multiselect = True, _
.FileName = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory)}
If fbd.ShowDialog = DialogResult.OK Then
CheckedListBox1.Items.AddRange(fbd.FileNames.Select(Function(f) IO.Path.GetFileName(f)).ToArray)
End If
发布于 2015-08-29 16:57:15
使用InitialDirectory
属性和一个临时全局字符串变量来记住最后一个打开的目录。
Dim LastDir As String = ""
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim fbd As New OpenFileDialog
If LastDir = "" Then Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory)
With fbd
.Title = "Select multiple files" ' Title of your dialog box
.InitialDirectory = LastDir ' Directory appear when you open your dialog.
.Multiselect = True 'allow user to select multiple items (files)
End With
If fbd.ShowDialog() = Windows.Forms.DialogResult.OK Then ' check user click ok or cancel
LastDir = Path.GetDirectoryName(fbd.FileName) 'Update your last Directory.
' do your stuf here i.e add selected files to listbox etc.
For Each mFile As String In fbd.FileNames
CheckedListBox1.Items.Add(mFile, True)
Next
End If
这将记住在程序运行/活动时最后一个打开的目录。如果要使用对话框,请始终记住上次打开的目录,在程序设置或计算机注册表中存储LastDir
。
https://stackoverflow.com/questions/32288216
复制相似问题