count

mirzao

Active member
Joined
Nov 10, 2005
Messages
44
Location
Malaysia
Programming Experience
Beginner
i have this code
For Each str As String In listbox1.Items
If str = "503" Then count += 1
Next


but how if I want to increment the count every time it sees 503 or 30A or 707? I tried to use "or" and "," in between but doesn't work. And one more thing, if there is an error "Cast from string "30A" to type 'Double' is not valid." what should I do?

 
VB.NET:
For Each str As String In listbox1.Items
  If str = "503" or str = "30A" or str = "707" Then 
    count += 1
  End If
Next

What about that cast? what line of code does it happen?
 
Nested If statements will work

VB.NET:
        For Each str As String In listbox1.Items
            If str = "503" Then
                count += 1
            ElseIf str = "30A" Then
                count += 1
            ElseIf str = "707" Then
                count += 1
            Else

            End If
        Next

This is a better option if you are doing different things when the string is different, ie. seperate counts for 503, 30A and 707.
 
Last edited:
so will select case:
VB.NET:
For Each str As String In listbox1.Items
  Select Case str
  Case "503", "30A", "707"
    count += 1
  End Select
Next
 
I would use the same code but with short circuit if statements.

For Each str As String In listbox1.Items
If str = "503" orelse str = "30A" orelse str = "707" Then
count += 1
End If
Next

This will work just like the nested if statements, without the ability to use different counters for each type, and will run a little faster. WHen you short circuit it stops testing throughout the if statement whenever it's true. In this example is str = "30A" then it would try, "503" = false, "30A" = true then go on without continuing to the next orelse. Without else it will test all the values even though it gets a true statement. This can speed up the app if tested on a large scale. Also, remember to put the most likely words first. For example if you predit that "30A" is going to appear more often than "503" then test teh "30A" first.

Another thing I would do which I have found also increases performance is to assign the listbox1.items to an array then use that string array in the loop for example.

Dim LB1(listbox1.items.count - 1) as string
LB1 = listbox1.items
For Each str As String In LB1
If str = "503" OrElse str = "30A" OrElse str = "707" Then
count += 1
End If
Next

This example isn't necessary if your working with a rather small listbox, but if your reading out a lot of data this will speed up the process.
 
Last edited:
ImDaFrEaK said:
Dim LB1(listbox1.items.count - 1) as string
LB1 = listbox1.items
That's all well and good but there's no way known that that code is going to work. You cannot implicitly convert a ListBox.ObjectCollection to an array of String, even with Option Strict turned Off. For a start, a ListBox.ObjectCollection doesn't necessarily contain String objects.
 
Back
Top