我的ListView回调检索子项有什么问题?

时间:2009-05-24 02:33:10

标签: .net winforms .net-3.5 listview callback

我正在尝试从另一个线程中检索ListView中的SubItem,但我不断获取Item而不是SubItem。我不确定如何正确编码。以下是我正在使用的代码:

Delegate Function lvExtractedCallback(ByVal x As Integer) As String

Private Function lvExtracted(ByVal x As Integer) As String
    Static Dim lvName As String

    If Me.OptionsList.InvokeRequired Then
        Dim lvEC As New lvExtractedCallback(AddressOf lvExtracted)
        Me.Invoke(lvEC, (New Object() {x}))
    Else
        lvName = OptionsList.Items.Item(x).SubItems.Item(0).Text
    End If
    Return lvName
End Function

Private Sub GetSubItem()
    Dim subItemText as String
    For i as Integer = 0 to 15
        subItemText = lvExtracted(x)
        Debug.Print subItemText
    Next
End Sub

1 个答案:

答案 0 :(得分:1)

代码只获取ListViewItem的主文本,因为每次都为第X个项返回SubItem.Item(0)。 SubItem.Item(0)是Item的Text字段。如果您只想获得第一个子项,则将SubItem.Item(0)更改为SubItems.Item(1)。如果您想获得任意子项,请参阅下面的示例。

来自MSDN:

The first subitem in the ListViewItem::ListViewSubItemCollection is always 
the item that owns the subitems. When performing operations on subitems in the
collection, be sure to reference index position 1 instead of 0 to make changes
to the first subitem.

〔实施例:

Delegate Function lvExtractedCallback(ByVal x As Integer, ByVal y As Integer) As String

Private Function lvExtracted(ByVal x As Integer, ByVal y As Integer) As String
    Static Dim lvName As String

    If Me.OptionsList.InvokeRequired Then
        Dim lvEC As New lvExtractedCallback(AddressOf lvExtracted)
        Me.Invoke(lvEC, (New Object() {x, y}))  '<-- This may need to be fixed, I'm rusty at VB.
    Else
        lvName = OptionsList.Items.Item(x).SubItems.Item(y).Text
    End If
    Return lvName
End Function