将文件路径添加到列表框项目

时间:2014-04-21 19:56:47

标签: vb.net visual-studio-2012 listbox

我正在尝试将文件路径存储在列表框项的标记中。

我正在使用以下内容搜索并将所需的文件夹名称添加到列表框

我已将ListBox1.Tag = sDir行添加到第一个Next之上,当我执行代码时,sDir的值似乎保留了路径,但是如果我创建一个简单{ {1}}弹出一个带有文件路径的消息框的事件只显示列表中的第一个文件夹名称。

任何提示或建议 - 我基本上想要选择一个列表框项目并让它指向它的路径!

谢谢

Double click

1 个答案:

答案 0 :(得分:1)

您可以将对象存储为项目,因此可以使用一个小类来存储项目信息:

Public Class myClass
    Public Property FileName as String
    Public Property PathName As String
    Public Foo As Integer

    ' class is invalid w/o file and path:
    Public Sub New(fName As String, pName As String)
         FileName = FName
         PathName = pName
    End Sub


    ' this will cause the filename to show in the listbox
    Public Overrides Function ToString() AS String
         Return FileName
    End Sub
 End Class

现在,您可以在加载/找到它们时将它们存储在列表框中:

 Dim El as MyClass           ' temp var for posting to listbox

 ' in the loop:
 El = New MyClass(filename, pathName)    ' use names from your Dir/File objects
 ListBox1.Items.Add(El)

并将其取回:

 ' INDEX_TO_READ is a dummy var of the index you want to get
 ' SelectedItem will also work
 thisFile = Ctype(ListBox1.Items(INDEX_TO_READ), MyClass).FileName
 thisPath = Ctype(ListBox1.Items(INDEX_TO_READ), MyClass).PathName
 ' or:
 Dim aFile As myClass = Ctype(ListBox1.Items(INDEX_TO_READ), MyClass)
相关问题