Who_Knock68
Who_Knock68

Reputation: 3

How to count selected items in the listbox by just select and see result in a label?

getting the logic of counting is easy but in practice it gets hard sometimes.

enter image description here

Now I've a list with many items on it. how to count those items if there were repeated and i want to convert that to a number using the FOR loop since i know how many items in the list.

I tried some codes but i did not succeed

'''''''''''''''
' 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

for EX: i wanna count the word "michigan " how many times repeated in the list by just clicking on it ?

Upvotes: 0

Views: 1377

Answers (2)

Idle_Mind
Idle_Mind

Reputation: 39142

Here's an example using Jim Hewitt's comment:

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

Edit

Here's an equivalent, manual, indexed for loop:

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

Upvotes: 1

K.Madden
K.Madden

Reputation: 210

 Dim count As Integer = 0
        For Each n As String In ListBox1.Items
            If n = "red" Then
                count += 1
            End If
        Next

        lblOutput.Text(count)

something like this do you mean?

Upvotes: 0

Related Questions