将子项添加到列表视图

时间:2013-03-14 19:26:48

标签: vb.net listview backgroundworker

我正在使用backgroundworker来填充列表视图,但我也想添加子项目。任何人都可以帮助我吗?

    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

2 个答案:

答案 0 :(得分:2)

For Each循环中尝试此操作:

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

li.Add(NewItem) 

希望这应该成功

答案 1 :(得分:1)

这也有效,但它是否正确?

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