The While Statement evaluates something which is true, and it will keep looping until false.
While True End While
Create a new VB Console and name it While Statement. Copy the following:
Dim mynum As Integer mynum = 25 While mynum < 100 mynum = mynum + 1 Console.WriteLine(mynum) End While Console.ReadLine()
You will just see a list of numbers from 26 to 100. We used the less than operator in this example, and the condition says “While 25 is less than 100”. It will increment 25 by 1, and once 25 = 100 it will stop because the condition becomes false.
While mynum < 100 mynum = mynum + 1 Console.WriteLine(mynum) If mynum = 51 Then Exit While End If End While
This is similar to the above statement, however the statement will stop executing once it reaches 51. The End While is required, as it terminates the while block once the condition is false. The Exit While stops execution immediately and continues to the next statement.
You can use the Exit While statement to stop the loop once a certain condition is met. In the following example, we ask the user for their age and increment by 1 until it reaches 5000 and then exit the loop.
Dim age As Integer Console.WriteLine("enter age") age = Console.ReadLine() While age > 10 age += 1 Console.WriteLine(age) If age = 5000 Then Exit While End If End While Console.ReadLine()
In this example we ask the user for their age, and if it is greater than 10 we increment it until it reaches 5000. We use an If Statement to see if age equals 5000; if it does we exit the While Statement.
You can use the following operators in a While Statement:
|<||Less than||While 10 < 20|
|>||Greater than||While 20 > 10|
|<=||Less than or equal to||While 20 <= 15|
|>=||Greater than or equal to||While 20 >= 15|
|=||Equal to||While age = 20|
|<>||Not equal to||While age <> 10|
Read a file
Create a text file and name it note.txt, insert some content and save in on the desktop. Next, insert the following above Module Module1:
This imports the Input / Output namespace, which allows us to read and write files.Below that, add:
Dim path = "U:\users\Asim Rehman\desktop\note.txt" Dim sr As New StreamReader(path) Dim line = sr.ReadToEnd() While line IsNot Nothing Console.WriteLine(line) Exit While End While Console.ReadLine()
- First import the namespace System.IO (it has the streamreader/writer class)
- Next set your path as a string
- Intialize the string sr
- Create a new string line which reads the file to the end
- Next is the While Statement which has IsNot Nothing. This makes sure the file is not empty.
- Print out the file contents to the end
- Exit the While Statement
- If you do not exit the While Statement it will keep looping
This tutorial covered how to use Visual Basic While Statements, and you learned how to loop through numbers, how to read a text file as well as how to exit a loop.