Adding file path to listbox item

2019-03-06 02:28发布

问题:

I'm trying to store the file path in a tag of a listbox item.

I'm using the below to search through and add the desired folder name to the list box

I've added the ListBox1.Tag = sDir line to above the first Next and when I step thorugh the code the value of sDir appears to hold the path however if I create a simple Double click event that pops up a message box with the file path in it only shows the first folder name in the list.

Any tips or advice - I basically want to select a Listbox item and have it point to its path!

Thanks

 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

回答1:

You can store objects as items, so a small class to store item info:

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

You can now store these in the listbox as you load/find them:

 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)

and to get it back:

 ' 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)