Sideway
output.to from Sideway
Draft for Information Only

Content

VB.NET Control Flow Statements
 Decision Structures
 If...Then...Else Construction
 Select...Case Construction
 Try...Catch...Finally Construction
 See also
 Loop Structures
 While Loops
 Do Loops
 For Loops
 For Each Loops
 See also
 Walkthrough: Implementing IEnumerable(Of T)
 Creating the Enumerable Class
 Using the Sample Iterator
 See also
 Other Control Structures
 Using...End Using Construction
 With...End With Construction
 See also
 How to: Dispose of a System Resource
  To dispose of a database connection when your code is finished with it
 See also
 Nested Control Structures
 Nesting Levels
 Nesting Different Kinds of Control Structures
 Overlapping Control Structures
 See also
 Related Sections
  Source/Reference

VB.NET Control Flow Statements

Left unregulated, a program proceeds through its statements from beginning to end. Some very simple programs can be written with only this unidirectional flow. However, much of the power and utility of any programming language comes from the ability to change execution order with control statements and loops.

Control structures allow you to regulate the flow of your program's execution. Using control structures, you can write Visual Basic code that makes decisions or that repeats actions. Other control structures let you guarantee disposal of a resource or run a series of statements on the same object reference.

Decision Structures

Visual Basic lets you test conditions and perform different operations depending on the results of that test. You can test for a condition being true or false, for various values of an expression, or for various exceptions generated when you execute a series of statements.

The following illustration shows a decision structure that tests for a condition being true and takes different actions depending on whether it is true or false.

A flow chart of an If...Then...Else construction.

If...Then...Else Construction

If...Then...Else constructions let you test for one or more conditions and run one or more statements depending on each condition. You can test conditions and take actions in the following ways:

  • Run one or more statements if a condition is True

  • Run one or more statements if a condition is False

  • Run some statements if a condition is True and others if it is False

  • Test an additional condition if a prior condition is False

The control structure that offers all these possibilities is the If...Then...Else Statement. You can use a single-line version if you have just one test and one statement to run. If you have a more complex set of conditions and actions, you can use the multiple-line version.

Select...Case Construction

The Select...Case construction lets you evaluate an expression one time and run different sets of statements based on different possible values. For more information, see Select...Case Statement.

Try...Catch...Finally Construction

Try...Catch...Finally constructions let you run a set of statements under an environment that retains control if any one of your statements causes an exception. You can take different actions for different exceptions. You can optionally specify a block of code that runs before you exit the whole Try...Catch...Finally construction, regardless of what occurs. For more information, see Try...Catch...Finally Statement.

Note

For many control structures, when you click a keyword, all of the keywords in the structure are highlighted. For instance, when you click If in an If...Then...Else construction, all instances of If, Then, ElseIf, Else, and End If in the construction are highlighted. To move to the next or previous highlighted keyword, press CTRL+SHIFT+DOWN ARROW or CTRL+SHIFT+UP ARROW.

See also

Loop Structures

Visual Basic loop structures allow you to run one or more lines of code repetitively. You can repeat the statements in a loop structure until a condition is True, until a condition is False, a specified number of times, or once for each element in a collection.

The following illustration shows a loop structure that runs a set of statements until a condition becomes true:

Flow chart that shows a Do...Until loop.

While Loops

The While...End While construction runs a set of statements as long as the condition specified in the While statement is True. For more information, see While...End While Statement.

Do Loops

The Do...Loop construction allows you to test a condition at either the beginning or the end of a loop structure. You can also specify whether to repeat the loop while the condition remains True or until it becomes True. For more information, see Do...Loop Statement.

For Loops

The For...Next construction performs the loop a set number of times. It uses a loop control variable, also called a counter, to keep track of the repetitions. You specify the starting and ending values for this counter, and you can optionally specify the amount by which it increases from one repetition to the next. For more information, see For...Next Statement.

For Each Loops

The For Each...Next construction runs a set of statements once for each element in a collection. You specify the loop control variable, but you do not have to determine starting or ending values for it. For more information, see For Each...Next Statement.

See also

Walkthrough: Implementing IEnumerable(Of T)

The IEnumerable<T> interface is implemented by classes that can return a sequence of values one item at a time. The advantage of returning data one item at a time is that you do not have to load the complete set of data into memory to work with it. You only have to use sufficient memory to load a single item from the data. Classes that implement the IEnumerable(T) interface can be used with For Each loops or LINQ queries.

For example, consider an application that must read a large text file and return each line from the file that matches particular search criteria. The application uses a LINQ query to return lines from the file that match the specified criteria. To query the contents of the file by using a LINQ query, the application could load the contents of the file into an array or a collection. However, loading the whole file into an array or collection would consume far more memory than is required. The LINQ query could instead query the file contents by using an enumerable class, returning only values that match the search criteria. Queries that return only a few matching values would consume far less memory.

You can create a class that implements the IEnumerable<T> interface to expose source data as enumerable data. Your class that implements the IEnumerable(T) interface will require another class that implements the IEnumerator<T> interface to iterate through the source data. These two classes enable you to return items of data sequentially as a specific type.

In this walkthrough, you will create a class that implements the IEnumerable(Of String) interface and a class that implements the IEnumerator(Of String) interface to read a text file one line at a time.

Note

Your computer might show different names or locations for some of the Visual Studio user interface elements in the following instructions. The Visual Studio edition that you have and the settings that you use determine these elements. For more information, see Personalizing the IDE.

Creating the Enumerable Class

Create the enumerable class project

  1. In Visual Basic, on the File menu, point to New and then click Project.

  2. In the New Project dialog box, in the Project Types pane, make sure that Windows is selected. Select Class Library in the Templates pane. In the Name box, type StreamReaderEnumerable, and then click OK. The new project is displayed.

  3. In Solution Explorer, right-click the Class1.vb file and click Rename. Rename the file to StreamReaderEnumerable.vb and press ENTER. Renaming the file will also rename the class to StreamReaderEnumerable. This class will implement the IEnumerable(Of String) interface.

  4. Right-click the StreamReaderEnumerable project, point to Add, and then click New Item. Select the Class template. In the Name box, type StreamReaderEnumerator.vb and click OK.

The first class in this project is the enumerable class and will implement the IEnumerable(Of String) interface. This generic interface implements the IEnumerable interface and guarantees that consumers of this class can access values typed as String.

Add the code to implement IEnumerable

  1. Open the StreamReaderEnumerable.vb file.

  2. On the line after Public Class StreamReaderEnumerable, type the following and press ENTER.

    VB
    Implements IEnumerable(Of String)
    

    Visual Basic automatically populates the class with the members that are required by the IEnumerable(Of String) interface.

  3. This enumerable class will read lines from a text file one line at a time. Add the following code to the class to expose a public constructor that takes a file path as an input parameter.

    VB
    Private _filePath As String
    
    Public Sub New(ByVal filePath As String)
        _filePath = filePath
    End Sub
    
  4. Your implementation of the GetEnumerator method of the IEnumerable(Of String) interface will return a new instance of the StreamReaderEnumerator class. The implementation of the GetEnumerator method of the IEnumerable interface can be made Private, because you have to expose only members of the IEnumerable(Of String) interface. Replace the code that Visual Basic generated for the GetEnumerator methods with the following code.

    VB
    Public Function GetEnumerator() As IEnumerator(Of String) _
        Implements IEnumerable(Of String).GetEnumerator
    
        Return New StreamReaderEnumerator(_filePath)
    End Function
    
    Private Function GetEnumerator1() As IEnumerator _
        Implements IEnumerable.GetEnumerator
    
        Return Me.GetEnumerator()
    End Function
    

Add the code to implement IEnumerator

  1. Open the StreamReaderEnumerator.vb file.

  2. On the line after Public Class StreamReaderEnumerator, type the following and press ENTER.

    VB
    Implements IEnumerator(Of String)
    

    Visual Basic automatically populates the class with the members that are required by the IEnumerator(Of String) interface.

  3. The enumerator class opens the text file and performs the file I/O to read the lines from the file. Add the following code to the class to expose a public constructor that takes a file path as an input parameter and open the text file for reading.

    VB
  4. Private _sr As IO.StreamReader
    
    Public Sub New(ByVal filePath As String)
        _sr = New IO.StreamReader(filePath)
    End Sub
    
  5. The Current properties for both the IEnumerator(Of String) and IEnumerator interfaces return the current item from the text file as a String. The implementation of the Current property of the IEnumerator interface can be made Private, because you have to expose only members of the IEnumerator(Of String) interface. Replace the code that Visual Basic generated for the Current properties with the following code.

    VB
  6. Private _current As String
    
    Public ReadOnly Property Current() As String _
        Implements IEnumerator(Of String).Current
    
        Get
            If _sr Is Nothing OrElse _current Is Nothing Then
                Throw New InvalidOperationException()
            End If
    
            Return _current
        End Get
    End Property
    
    Private ReadOnly Property Current1() As Object _
        Implements IEnumerator.Current
    
        Get
            Return Me.Current
        End Get
    End Property
    
  7. The MoveNext method of the IEnumerator interface navigates to the next item in the text file and updates the value that is returned by the Current property. If there are no more items to read, the MoveNext method returns False; otherwise the MoveNext method returns True. Add the following code to the MoveNext method.

    VB
  8. Public Function MoveNext() As Boolean _
        Implements System.Collections.IEnumerator.MoveNext
    
        _current = _sr.ReadLine()
        If _current Is Nothing Then Return False
        Return True
    End Function
    
  9. The Reset method of the IEnumerator interface directs the iterator to point to the start of the text file and clears the current item value. Add the following code to the Reset method.

    VB
  10. Public Sub Reset() _
        Implements System.Collections.IEnumerator.Reset
    
        _sr.DiscardBufferedData()
        _sr.BaseStream.Seek(0, IO.SeekOrigin.Begin)
        _current = Nothing
    End Sub
    
  11. The Dispose method of the IEnumerator interface guarantees that all unmanaged resources are released before the iterator is destroyed. The file handle that is used by the StreamReader object is an unmanaged resource and must be closed before the iterator instance is destroyed. Replace the code that Visual Basic generated for the Dispose method with the following code.

    VB
    Private disposedValue As Boolean = False
    
    Protected Overridable Sub Dispose(ByVal disposing As Boolean)
        If Not Me.disposedValue Then
            If disposing Then
                ' Dispose of managed resources.
            End If
            _current = Nothing
            _sr.Close()
            _sr.Dispose()
        End If
    
        Me.disposedValue = True
    End Sub
    
    Public Sub Dispose() Implements IDisposable.Dispose
        Dispose(True)
        GC.SuppressFinalize(Me)
    End Sub
    
    Protected Overrides Sub Finalize()
        Dispose(False)
    End Sub
    

Using the Sample Iterator

You can use an enumerable class in your code together with control structures that require an object that implements IEnumerable, such as a For Next loop or a LINQ query. The following example shows the StreamReaderEnumerable in a LINQ query.

VB
Dim adminRequests = 
    From line In New StreamReaderEnumerable("..\..\log.txt")
    Where line.Contains("admin.aspx 401")

Dim results = adminRequests.ToList()

See also

Other Control Structures

Visual Basic provides control structures that help you dispose of a resource or reduce the number of times you have to repeat an object reference.

Using...End Using Construction

The Using...End Using construction establishes a statement block within which you make use of a resource such as a SQL connection. You can optionally acquire the resource with the Using statement. When you exit the Using block, Visual Basic automatically disposes of the resource so that it is available for other code to use. The resource must be local and disposable. For more information, see Using Statement.

With...End With Construction

The With...End With construction lets you specify an object reference once and then run a series of statements that access its members. This can simplify your code and improve performance because Visual Basic does not have to re-establish the reference for each statement that accesses it. For more information, see With...End With Statement.

See also

How to: Dispose of a System Resource

You can use a Using block to guarantee that the system disposes of a resource when your code exits the block. This is useful if you are using a system resource that consumes a large amount of memory, or that other components also want to use.

To dispose of a database connection when your code is finished with it

  1. Make sure you include the appropriate Imports Statement (.NET Namespace and Type) for the database connection at the beginning of your source file (in this case, System.Data.SqlClient).

  2. Create a Using block with the Using and End Using statements. Inside the block, put the code that deals with the database connection.

  3. Declare the connection and create an instance of it as part of the Using statement.

  1. ' Insert the following line at the beginning of your source file.  
    Imports System.Data.SqlClient  
    Public Sub AccessSql(ByVal s As String)  
        Using sqc As New System.Data.SqlClient.SqlConnection(s)  
            MsgBox("Connected with string """ & sqc.ConnectionString & """")  
        End Using  
    End Sub  
    

    The system disposes of the resource no matter how you exit the block, including the case of an unhandled exception.

    Note that you cannot access sqc from outside the Using block, because its scope is limited to the block.

    You can use this same technique on a system resource such as a file handle or a COM wrapper. You use a Using block when you want to be sure to leave the resource available for other components after you have exited the Using block.

See also

Nested Control Structures

You can place control statements inside other control statements, for example an If...Then...Else block within a For...Next loop. A control statement placed inside another control statement is said to be nested.

Nesting Levels

Control structures in Visual Basic can be nested to as many levels as you want. It is common practice to make nested structures more readable by indenting the body of each one. The integrated development environment (IDE) editor automatically does this.

In the following example, the procedure sumRows adds together the positive elements of each row of the matrix.

VB
Public Sub sumRows(ByVal a(,) As Double, ByRef r() As Double)  
    Dim i, j As Integer  
    For i = 0 To UBound(a, 1)  
        r(i) = 0  
        For j = 0 To UBound(a, 2)  
            If a(i, j) > 0 Then  
                r(i) = r(i) + a(i, j)  
            End If  
        Next j  
    Next i  
End Sub  

In the preceding example, the first Next statement closes the inner For loop and the last Next statement closes the outer For loop.

Likewise, in nested If statements, the End If statements automatically apply to the nearest prior If statement. Nested Do loops work in a similar fashion, with the innermost Loop statement matching the innermost Do statement.

Note

For many control structures, when you click a keyword, all of the keywords in the structure are highlighted. For instance, when you click If in an If...Then...Else construction, all instances of If, Then, ElseIf, Else, and End If in the construction are highlighted. To move to the next or previous highlighted keyword, press CTRL+SHIFT+DOWN ARROW or CTRL+SHIFT+UP ARROW.

Nesting Different Kinds of Control Structures

You can nest one kind of control structure within another kind. The following example uses a With block inside a For Each loop and nested If blocks inside the With block.

VB
For Each ctl As System.Windows.Forms.Control In Me.Controls  
    With ctl  
        .BackColor = System.Drawing.Color.Yellow  
        .ForeColor = System.Drawing.Color.Black  
        If .CanFocus Then  
            .Text = "Colors changed"  
            If Not .Focus() Then  
                ' Insert code to process failed focus.  
            End If  
        End If  
    End With  
Next ctl  

Overlapping Control Structures

You cannot overlap control structures. This means that any nested structure must be completely contained within the next innermost structure. For example, the following arrangement is invalid because the For loop terminates before the inner With block terminates.

Diagram that shows an example of invalid nesting.

The Visual Basic compiler detects such overlapping control structures and signals a compile-time error.

See also

Related Sections

Control Flow Summary

Source/Reference


©sideway

ID: 200900016 Last Updated: 9/16/2020 Revision: 0 Ref:

close

References

  1. Active Server Pages,  , http://msdn.microsoft.com/en-us/library/aa286483.aspx
  2. ASP Overview,  , http://msdn.microsoft.com/en-us/library/ms524929%28v=vs.90%29.aspx
  3. ASP Best Practices,  , http://technet.microsoft.com/en-us/library/cc939157.aspx
  4. ASP Built-in Objects,  , http://msdn.microsoft.com/en-us/library/ie/ms524716(v=vs.90).aspx
  5. Response Object,  , http://msdn.microsoft.com/en-us/library/ms525405(v=vs.90).aspx
  6. Request Object,  , http://msdn.microsoft.com/en-us/library/ms524948(v=vs.90).aspx
  7. Server Object (IIS),  , http://msdn.microsoft.com/en-us/library/ms525541(v=vs.90).aspx
  8. Application Object (IIS),  , http://msdn.microsoft.com/en-us/library/ms525360(v=vs.90).aspx
  9. Session Object (IIS),  , http://msdn.microsoft.com/en-us/library/ms524319(8v=vs.90).aspx
  10. ASPError Object,  , http://msdn.microsoft.com/en-us/library/ms524942(v=vs.90).aspx
  11. ObjectContext Object (IIS),  , http://msdn.microsoft.com/en-us/library/ms525667(v=vs.90).aspx
  12. Debugging Global.asa Files,  , http://msdn.microsoft.com/en-us/library/aa291249(v=vs.71).aspx
  13. How to: Debug Global.asa files,  , http://msdn.microsoft.com/en-us/library/ms241868(v=vs.80).aspx
  14. Calling COM Components from ASP Pages,  , http://msdn.microsoft.com/en-us/library/ms524620(v=VS.90).aspx
  15. IIS ASP Scripting Reference,  , http://msdn.microsoft.com/en-us/library/ms524664(v=vs.90).aspx
  16. ASP Keywords,  , http://msdn.microsoft.com/en-us/library/ms524672(v=vs.90).aspx
  17. Creating Simple ASP Pages,  , http://msdn.microsoft.com/en-us/library/ms524741(v=vs.90).aspx
  18. Including Files in ASP Applications,  , http://msdn.microsoft.com/en-us/library/ms524876(v=vs.90).aspx
  19. ASP Overview,  , http://msdn.microsoft.com/en-us/library/ms524929(v=vs.90).aspx
  20. FileSystemObject Object,  , http://msdn.microsoft.com/en-us/library/z9ty6h50(v=vs.84).aspx
  21. http://msdn.microsoft.com/en-us/library/windows/desktop/ms675944(v=vs.85).aspx,  , ADO Object Model
  22. ADO Fundamentals,  , http://msdn.microsoft.com/en-us/library/windows/desktop/ms680928(v=vs.85).aspx
close

Latest Updated LinksValid XHTML 1.0 Transitional Valid CSS!Nu Html Checker Firefox53 Chromena IExplorerna
IMAGE

Home 5

Business

Management

HBR 3

Information

Recreation

Hobbies 8

Culture

Chinese 1097

English 339

Reference 79

Computer

Hardware 249

Software

Application 213

Digitization 32

Latex 52

Manim 205

KB 1

Numeric 19

Programming

Web 289

Unicode 504

HTML 66

CSS 65

SVG 46

ASP.NET 270

OS 429

DeskTop 7

Python 72

Knowledge

Mathematics

Formulas 8

Algebra 84

Number Theory 206

Trigonometry 31

Geometry 34

Coordinate Geometry 2

Calculus 67

Complex Analysis 21

Engineering

Tables 8

Mechanical

Mechanics 1

Rigid Bodies

Statics 92

Dynamics 37

Fluid 5

Fluid Kinematics 5

Control

Process Control 1

Acoustics 19

FiniteElement 2

Natural Sciences

Matter 1

Electric 27

Biology 1

Geography 1


Copyright © 2000-2024 Sideway . All rights reserved Disclaimers last modified on 06 September 2019