Thomas06501
Thomas06501

Reputation: 11

How to search for Text in a ListBox?

So here's what my program looks

Click this

What i want to do is search for how many occurrences there are of one grade

Here's the code a friend helped me do

Private Function countOccOfMark(ByVal mark As String)
    Dim resultCount As Integer = 0

    For cnt As Integer = 0 To lstDisplay.Items.Count - 1
        Dim gradeMark As String = lstDisplay.Items(cnt)
        Dim results() As String = gradeMark.Split(vbTab)

        For Each res As String In results
            If (res = mark) Then
                resultCount = resultCount + 1
            End If
        Next
    Next

    Return resultCount
End Function


Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim mark As String = InputBox("Enter a Grade to search for")
    Dim amountFound As Integer = countOccOfMark(mark)
    MessageBox.Show("Found " & amountFound & " Occurences of the mark " & mark)
End Sub

Which works fine but I'm sure there's a easier way to do it

Upvotes: 1

Views: 77

Answers (1)

JerryM
JerryM

Reputation: 885

The inner For-Next is unnecessary. The grade is always in the second column.

Private Function countOccOfMark(ByVal mark As String)
    Dim resultCount As Integer = 0

    For cnt As Integer = 0 To lstDisplay.Items.Count - 1
        Dim gradeMark As String = lstDisplay.Items(cnt)
        Dim results() As String = gradeMark.Split(vbTab)
        If results(1) = mark Then
            resultCount = resultCount + 1
        End If
    Next

    Return resultCount
End Function

Upvotes: 1

Related Questions