Visual Basic.Net ListView项目

时间:2013-12-24 07:10:00

标签: vb.net listview

Dim item = ListView2.Items.Add("...")
    For cnt As Integer = 1 To ListView2.Columns.Count
        item.SubItems.Add("")
    Next
    If ListView2.FocusedItem.ImageIndex = 10 Then
        If TextBox2.Text.Length < 4 Then
            TextBox2.Text = ""
        End If
    End If

我得到的错误是:

If ListView2.FocusedItem.ImageIndex = 10 Then

错误名称:对象引用未设置为对象的实例

=============================================== =====================

这就是它的真实面貌:

Private Sub ListView2_DoubleClick(sender As Object, e As EventArgs) Handles ListView2.DoubleClick
    If ListView2.FocusedItem.ImageIndex = 0 Or ListView2.FocusedItem.ImageIndex = 1 Or ListView2.FocusedItem.ImageIndex = 2 Then
        If TextBox2.Text.Length = 0 Then
            TextBox2.Text += ListView2.FocusedItem.Text
        Else
            TextBox2.Text += ListView2.FocusedItem.Text & "\"
        End If
        RefreshList()
    End If
    'from here doesn't work
    If Not IsNothing(ListView2.FocusedItem) AndAlso ListView2.FocusedItem.ImageIndex = 10 Then
        If TextBox2.Text.Length < 4 Then
            TextBox2.Text = ""                
        Else
            TextBox2.Text = TextBox2.Text.Substring(0, TextBox2.Text.LastIndexOf("\"))
            TextBox2.Text = TextBox2.Text.Substring(0, TextBox2.Text.LastIndexOf("\") + 1)
            RefreshList()
        End If
    End If
End Sub

Public Sub RefreshList()
    ListView2.Items.Clear()
    Dim item = ListView2.Items.Add("...")
    For cnt As Integer = 1 To ListView2.Columns.Count
        item.SubItems.Add("")
    Next     
End Sub

1 个答案:

答案 0 :(得分:0)

在访问其属性(在本例中为ImageIndex属性)之前,尝试检查ListView2.FocusedItem以确保它不是Null / Nothing。 以下是如何添加检查的示例:

If Not IsNothing(ListView2.FocusedItem) AndAlso ListView2.FocusedItem.ImageIndex = 10 Then

只有在条件为真之前检查AndAlso之后的条件。