cjohnson2136
cjohnson2136

Reputation: 1591

While loop in VB.NET

I have some little issues with syntax. I am used to C# and just started VB.NET. I am trying to do a while loop when it loops through the items from a list. What is the syntax that I am doing wrong?

While oResponse.outputControl.Items(i) <> Nothing

    //Do something

End While

Upvotes: 1

Views: 6331

Answers (2)

Joel Coehoorn
Joel Coehoorn

Reputation: 415665

Don't forget to increment your counter:

While oResponse.outputControl.Items(i) <> Nothing

    'Do something
    i += 1

End While

and if this is a reference type (you didn't say, but it probably is), you can't compare it to Nothing with the <> operator:

While oResponse.outputControl.Items(i) IsNot Nothing

    'Do something
    i += 1

End While

But maybe what you really want is a For Each loop:

For Each Item In oResponse.outputControl.Items
    'Do Something
Next Item

And one more thing: what's with the hungarian wart in the oResponse variable? That style is no longer recommended, and Microsoft now even specifically recommends against it. VB.Net also has a feature called "Default properties" that just might make this even simpler. Pulling it all together (now including the ListItem type from your comment above):

For Each Item As ListItem In Response.outputControl
    'Do Something
Next Item

Upvotes: 6

alundy
alundy

Reputation: 857

Try:

While oResponse.outputControl.Items(i) Is Nothing

    'do something

End While

You could also do this if you wanted to be particularly old school:

Do

    'do something

Loop Until Not oResponse.outputControl.Items(i) Is Nothing

Upvotes: 0

Related Questions