2014-04-21 62 views
0

我试图将文件路径存储在列表框项目的标签中。将文件路径添加到列表框项目

我使用下面通过搜索并添加所需的文件夹名称列表框中

我已经添加了ListBox1.Tag = sDir线到第一Next上方,当我踏上thorugh代码sDir值似乎保留路径但是如果我创建一个简单的Double click事件,弹出消息框,其中的文件路径只显示列表中的第一个文件夹名称。

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

感谢

For Each Dir As String In System.IO.Directory.GetDirectories("c:\Working") 

     Dim dirInfo As New System.IO.DirectoryInfo(Dir) 

     For Each sDir As String In System.IO.Directory.GetDirectories(dirInfo.ToString) 

      Dim sdirInfo As New System.IO.DirectoryInfo(sDir) 

      ListBox1.Items.Add(sdirInfo.Name) 
      ListBox1.Tag = sDir 
     Next 

    Next 
+0

ListBox中的所有项目只有一个标签,因此如果项目可能有不同的路径不会工作。您可以将对象存储为项目,以便您可以编写一个简单的类来存储文件名,路径以及任何其他项作为每个项目。 – Plutonix

回答

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) 
+0

感谢您的帮助 - 真的很感激。我错过了一些非常简单的事情,因为我得到了El,文件名,路径名和INDEX_TO_READ,因为'没有声明'错误 – elmonko

+0

上面的代码更像是如何使用它们的片段*通常*而不是完成代码 - 我无法看到哪里文件名称来自。 INDEX_TO_READ是一个虚拟变量,您可以在其中使用列表项目的索引(或使用SelectedItem或SelectedIndex - 该点应显示如何将项目转换回myClass对象)。查看编辑。 – Plutonix

相关问题