如何仅通过选择并查看标签中的结果来计算列表框中的选定项目?

时间:2019-03-28 14:29:04

标签: vb.net

获得计数的逻辑很容易,但在实践中有时会变得困难。

enter image description here

现在,我有一个包含许多项目的列表。如果重复出现该如何计数那些项目,我想使用FOR循环将其转换为数字,因为我知道列表中有多少项目。

我尝试了一些代码,但没有成功

'''''''''''''''
' VB 2015
''''''''''''
Public Class Form1
    Private Sub lstWinners_List_SelectedIndexChanged(sender As Object, e As EventArgs) Handles lstWinners_List.SelectedIndexChanged
        If lstWinners_List.SelectedIndex <> -1 Then

            Dim count As Integer = 0
            Dim strselection As String = lstWinners_List.Items(lstWinners_List.SelectedIndex).ToString
            For i As Integer = 0 To lstWinners_List.Items.Count - 1
                If lstWinners_List.Items(i) = strselection Then
                    count = count + 1
                End If
            Next
            lblOutput.Text = count.ToString
        End If
    End Sub
End Class

对于EX: 我想通过单击它来数数“密歇根”一词在列表中重复多少次?

2 个答案:

答案 0 :(得分:1)

这是一个使用吉姆·休伊特(Jim Hewitt)评论的示例:

Private Sub lstWinners_List_SelectedIndexChanged(sender As Object, e As EventArgs) Handles lstWinners_List.SelectedIndexChanged
    If lstWinners_List.SelectedIndex <> -1 Then
        Dim selection As String = lstWinners_List.Items(lstWinners_List.SelectedIndex).ToString
        Dim wins As Integer = (From team As String In lstWinners_List.Items Where team.Equals(selection)).Count
        lblOutput.Text = wins.ToString
    End If
End Sub

修改

这是一本等效的手册,为循环编入了索引:

Private Sub lstWinners_List_SelectedIndexChanged(sender As Object, e As EventArgs) Handles lstWinners_List.SelectedIndexChanged
    If lstWinners_List.SelectedIndex <> -1 Then
        Dim count As Integer = 0
        Dim selection As String = lstWinners_List.Items(lstWinners_List.SelectedIndex).ToString
        For i As Integer = 0 To lstWinners_List.Items.Count - 1
            If lstWinners_List.Items(i) = selection Then
                count = count + 1
            End If
        Next
        lblOutput.Text = count.ToString
    End If
End Sub

答案 1 :(得分:0)

 昏暗计数为整数= 0         对于ListBox1.Items中的每个n作为字符串             如果n =“ red”,则                 计数+ = 1             万一         下一个         lblOutput.Text(count) 你是这样说的吗?