简体   繁体   中英

add subitems to a listview

I'm using a backgroundworker to populate a listview, but i want to add subitems also. Can anyone help me out?

    Public Class Form1

    Private Sub bgw_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles bgw.DoWork
        Dim li As New List(Of ListViewItem)

        For Each fn As String In My.Computer.FileSystem.GetFiles("s:\Videos", FileIO.SearchOption.SearchAllSubDirectories, "*.*")
            li.Add(New ListViewItem(My.Computer.FileSystem.GetName(fn))) 
            'here i want to add a subitem containing the filesize
            'My.Computer.FileSystem.GetFileInfo(fn).Length
        Next

        e.Result = li.ToArray
    End Sub

    Private Sub bgw_RunWorkerCompleted(sender As Object, e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles bgw.RunWorkerCompleted
        lv.Items.AddRange(DirectCast(e.Result, ListViewItem()))
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        bgw.RunWorkerAsync()
    End Sub
End Class

Try this in your For Each loop:

Dim NewItem as New ListViewItem(My.Computer.FileSystem.GetName(fn))
NewItem.SubItems.Add(My.Computer.FileSystem.GetFileInfo(fn).Length)

li.Add(NewItem) 

Hopefully that should do the trick

this is working too, but is it correct?

Public Class Form1

    Dim item1 As String = ""
    Dim item2 As String = ""

    Private Sub bgw_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles bgw.DoWork
        Dim progress As Integer = 0
        'calculate progress later
        progress = 1

        For Each fn As String In My.Computer.FileSystem.GetFiles("s:\Videos", FileIO.SearchOption.SearchAllSubDirectories, "*.*")
            item1 = My.Computer.FileSystem.GetName(fn)
            item2 = My.Computer.FileSystem.GetFileInfo(fn).Length

            bgw.ReportProgress(progress)
        Next
    End Sub

    Private Sub bgw_ProgressChanged(sender As Object, e As System.ComponentModel.ProgressChangedEventArgs) Handles bgw.ProgressChanged
        Dim li As New ListViewItem
        li = lv.Items.Add(item1, 0)
        li.SubItems.Add(item2)
    End Sub

    Private Sub bgw_RunWorkerCompleted(sender As Object, e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles bgw.RunWorkerCompleted
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        lv.Items.Clear()
        bgw.RunWorkerAsync()
    End Sub

End Class

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM