Home
Search
 
What's New
Index
Books
Links
Q & A
Newsletter
Banners
 
Feedback
Tip Jar
 
C# Helper...
 
XML RSS Feed
Follow VBHelper on Twitter
 
 
MSDN Visual Basic Community
 
 
 
 
 
TitleBug: For Each loop in VB .NET doesn't end with variable equal to Nothing
Keywordsbug, loop, for each, ForEach, VB.NET
CategoriesBug Alerts, VB.NET
 
In VB 6, you can use code similar to the following to see if an object is in a collection.
 
For Each obj In values
    If obj.value = target_value Then Exit For
Next obj

If obj Is Nothing Then
    MsgBox "Not found"
Else
    MsgBox "Found"
End If
 
In VB .NET, if the target object doesn't appear in the collection the For Each loop finishes with the looping variable pointing to the last item in the collection. That means this code always thinks it has found the target object.

[Actually most languages including VB say that the value of the looping variable is not defined at the end of the loop and that you should not rely on it having a particular value. That's certainly the case here.]

Here's one way around this problem.

 
Dim obj As Object
Dim found_it As Object

found_it = Nothing
For Each obj In values
    If obj = txtValue.Text Then
        found_it = obj
        Exit For
    End If
Next obj

If found_it Is Nothing Then
    lblFoundIt.Text = "Not found"
Else
    lblFoundIt.Text = "Found"
End If
 
 
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated