Monday, 18 June 2012

How to use FOR NEXT loop in vb.net


For next is used for programming code to be repeat a task for more than one times or repeat a task till you reach a condition, use loop statements to achieve your desired results.
FOR NEXT Loop, FOR EACH Loop, WHILE Loop and DO WHILE Loop are the commonly used loops
FOR NEXT Loop:
The FOR NEXT Loop , execute the loop body the source code within For Next code block to a fixed number of times.
For  variable  = [start_value] to [End_value] step
‘Body of the loop
Next [variable]
Here
Variable  à The counter for the loop to repeat the steps.
Star_Value à The starting value assign to counter variable .
End_Value : When the counter variable reach end value the Loop will stop .
Body  of the loopà The source code between loop body
 

Public Class Form1
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim variable As Integer
        Dim start_Val As Integer
        Dim end_Val As Integer
        start_Val = 1
        end_Val = 5
        For variable = start_Val To end_Val
            MsgBox("Message Box Shows " & variable & " Times ")
        Next variable
    End Sub
End Class

When you execute this program, It will show message box five time and each time it shows the counter value.
If you want to Exit from FOR NEXT Loop even before completing the loop Visual Basic.NET provides a keyword Exit to use within the loop body.

Public Class Form1
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim variable As Integer
        Dim start_Val As Integer
        Dim end_Val As Integer
        start_Val = 1
        end_Val = 5
        For variable = start_Val To end_Val
            MsgBox("Message Box Shows " & variable & " Times ")
            If variable = 3 Then
                Exit For

            End If
        Next variable
    End Sub
End Class



When you execute this program, it will show message box three times and it will exit the for loop

No comments:

Post a Comment