如果选择了索引,则列表视图条件

listview condition if selected index

我有一个包含一些项目的视图列表

movies
music

代码:

当我 select 项目 0 是电影时,让我添加一个名为 The Matrix Resurrections 的新项目。

    For I As Integer = 0 To ListView1.Items.Count - 1
        If ListView1.Items(I).Index = 0 Then

            ListView1.Items.Add("The Matrix Resurrections")
        End if

不幸的是,它不像常规列表框那样工作。

ListView 有两个选项来管理 select离子:

现在,我们说的是 items 而不是 item 因为,默认情况下,您可以 select 列表框中的多个项目。如果要禁用多selection,请使用此代码:

ListView1.MultiSelect = False

现在,在您的 Sub(处理点击或 selectedIndexChanged 事件)中,您可以使用上述两个属性之一。例如:

Private Sub ListView1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListView1.SelectedIndexChanged
    If ListView1.SelectedItems.Count > 0 AndAlso ListView1.SelectedIndices(0) = 0 Then
        ListView1.Items.Add("The Matrix Resurrections")
    End If
End Sub

注意使用ListView1.SelectedItems

If no items are currently selected, an empty ListView.SelectedIndexCollection is returned

所以检查 ListView1.SelectedItems.Count > 0 可以防止错误。

输出