vb 2010 - 在listview

时间:2015-09-16 01:49:59

标签: vb.net

我已经设置了包含以下属性的列表视图:

FullRowSelect = True
GridLines = True
View = Details
HeaderStyle = Nonclickable
Multiselect = False

我创建了4列,并用10行数据填充它们。我想在每次单击列表视图中的行时获取行号。我这样做了如下:

Private Sub ListView1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ListView1.SelectedIndexChanged

indexNo = ListView1.FocusedItem.Index
label1.text = indexNo.ToString

End Sub

indexNo是一个公开声明的字符串。

当我点击列表视图中的另一行时,我收到以下错误:

NullReferenceException was unhandled
Object reference not set to an instance of an object.

1 个答案:

答案 0 :(得分:0)

确保首先选择某些内容:

    If Not IsNothing(ListView1.FocusedItem) Then
        indexNo = ListView1.FocusedItem.Index
        Label1.Text = indexNo.ToString
    End If

或者,检查SelectedIndices集合的长度:

    If ListView1.SelectedIndices.Count > 0 Then
        indexNo = ListView1.SelectedIndices(0)
        Label1.Text = indexNo.ToString
    End If