如您所见,问题在于仅文件名不足以删除文件。您还需要文件的完整路径。因此,您需要某种方式来存储整个路径,但只显示文件名。这也很重要,因为在不同的目录中可能有两个(或更多)同名文件。
ListBox 可以将其Datasource 属性设置为显示来自“实现 IList 或 IListSource 接口的对象,例如 DataSet 或 Array”的项目。
然后设置DisplayMember 和ValueMember 属性来告诉它要显示什么以及作为值给出什么。
例如,我创建了一个名为“FileItem”的类,它具有完整文件名的属性以及您想要显示的任何内容,用“FileItem”的实例填充了一个列表,并告诉 ListBox1 显示它:
Imports System.IO
Public Class Form1
Class FileItem
Property FullName As String
Property DisplayedName As String
Public Sub New(filename As String)
Me.FullName = filename
Me.DisplayedName = Path.GetFileNameWithoutExtension(filename)
End Sub
End Class
Private Sub PopulateDeletionList(dir As String, filter As String)
Dim files = Directory.EnumerateFiles(dir, filter, SearchOption.AllDirectories)
Dim fileNames = files.Select(Function(s) New FileItem(s)).ToList()
Dim bs As New BindingSource With {.DataSource = fileNames}
ListBox1.DataSource = bs
ListBox1.DisplayMember = "DisplayedName"
ListBox1.ValueMember = "FullName"
End Sub
Private Sub ListBox1_Click(sender As Object, e As EventArgs) Handles ListBox1.Click
Dim lb = DirectCast(sender, ListBox)
Dim sel = lb.SelectedIndex
If sel >= 0 Then
Dim fileToDelete = CStr(lb.SelectedValue)
Dim choice = MessageBox.Show("Do you really want to delete " & fileToDelete, "Confirm file delete", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
If choice = DialogResult.Yes Then
Try
File.Delete(fileToDelete)
lb.DataSource.RemoveAt(sel)
Catch ex As Exception
MessageBox.Show("Could not delete " & fileToDelete & " because " & ex.Message)
End Try
End If
End If
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
PopulateDeletionList("C:\temp", "*.txt")
End Sub
End Class
已编辑 我忘记从 ListBox 中删除该项目。为此,它需要通过 BindingSource 绑定到 DataSource。
额外功能 鉴于可能有多个同名文件,您可能需要在列表框项目中添加一个工具提示,以便您可以看到它所在的目录。请参阅@ 987654325@ 用于只需要稍作调整即可工作的实现,例如:
Dim toolTip As ToolTip = New ToolTip()
' ...
Private Sub ListBox1_MouseMove(sender As Object, e As MouseEventArgs) Handles ListBox1.MouseMove
Dim lb = DirectCast(sender, ListBox)
Dim index As Integer = lb.IndexFromPoint(e.Location)
If (index >= 0 AndAlso index < ListBox1.Items.Count) Then
Dim desiredTooltip = DirectCast(lb.Items(index), FileItem).FullName
If (toolTip.GetToolTip(lb) <> desiredTooltip) Then
toolTip.SetToolTip(lb, desiredTooltip)
End If
End If
End Sub