【问题标题】:Find the selected ListView item and then perform an action on click找到选定的 ListView 项,然后单击执行操作
【发布时间】:2020-12-16 21:10:29
【问题描述】:

我试过了:

 If ListView1.SelectedItems = 1 Then
        'do somehting
    ElseIf ListView1.SelectedItems = 2 Then
        'do something else
    Else
        'do another thing
    End If

但它没有用。谁能告诉我我做错了什么?

【问题讨论】:

  • SelectedItems 属性是一个集合,不能等于整数。您是要检查 ListItem 的 Text 的值还是 SelectedItems 集合的计数?

标签: vb.net winforms listview .net-5


【解决方案1】:

ListView 控件的SelectedItems 属性是一个集合(可能包含多个选定项)。

考虑一种情况,您可以控制 ListView1,并在表单加载事件中手动向其中添加项目,如下所示:

ListView1.Items.Add("Dog")
ListView1.Items.Add("Cat")
ListView1.Items.Add("Bird")

那么你就有了一个按钮控件Button1,它的点击事件代码如下:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim s As String = ""
    For Each item As ListViewItem In ListView1.SelectedItems
        s += item.Text + vbCrLf
    Next
    MsgBox(s)
End Sub

当您单击该按钮时,它会一次遍历所有选定项的集合,访问每个项的 .Text 属性并将它们添加到输出中。

因此,当您说“查找选定的列表视图项”时,可能有多个选定项,因此也许您可以更准确地解释一下您希望看到的点击发生的情况,因为该控件有多种可能适用的事件类型。前任。单击、ItemChecked、MouseClick、MouseDoubleClick 等。

更新:我可能误解了你的问题。请提供更多详细信息。

也许这就是你所追求的?

Private Sub ListView1_SelectedIndexChanged(sender As Object, e As ListViewItemSelectionChangedEventArgs) Handles ListView1.ItemSelectionChanged
    If e.Item.Text = "Dog" Then MsgBox("It's a dog")
End Sub

处理这些事件可能很棘手。例如,msgbox 会弹出你选择 dog。 But it also pops when the selection changes from dog to something else, because that's still a selection changed event.然而,这应该让你朝着正确的方向前进。您可能需要仔细查看不同的事件,以找出最适合您的情况的事件 - 您可能需要处理多个事件。

【讨论】:

    猜你喜欢
    • 2013-12-04
    • 1970-01-01
    • 2014-06-20
    • 1970-01-01
    • 2014-01-21
    • 1970-01-01
    • 1970-01-01
    • 2015-07-13
    相关资源
    最近更新 更多