我需要:单击按钮时打开文件对话框,然后我选择多个文件,然后单击确定,然后文件将出现在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
答案 0 :(得分:1)
我在测试中使用了List(of String),你可以改变它以满足你的需求。
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
答案 1 :(得分:0)
使用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
。