Saturday 15 September 2012

Assigning Values to an Array


There are a number of way you can put data into each position of an array. The code we just wrote for the two buttons had known values stored into each position. We knew we that we wanted the numbers 1 to 5 to be stored into our Integer array, and we knew that we wanted the text "This is a String Array" stored into our String array.

But you don't have to know what the values are. You can assign values straight from a Textbox into the position of your array. Like this:
MyNumbers(0) = Val(Textbox1.Text)
MyNumbers(1) = Val(Textbox2.Text)
etc
With that code, whatever you typed into the Textboxes on your Form would be stored into the positions of your array. The same would be true of a String Array:
MyNumbers(0) = Textbox1.Text
MyNumbers(1) = Textbox2.Text
etc
But do we have to keep typing out a value for each and every position of our array. What if we had an array with a hundred items in it, MyText(99)? Would we have to type out text for all one hundred positions of the array?
Well, obviously not. You can use code to assign values to your array. Here is an example where we don't type out values for all positions of an array. It's the times table again. This time we'll use an array. And we'll write a line of code to assign values to each position of the array.
  • First, add another Button to your form.
  • Set the Text Property to "Times TableArray"
  • Add a Textbox to your Form
  • Set the Text Property to a blank string (in other words, delete Textbox1 from the Text property)
  • Add a Label near the Textbox
  • Set the Text property of the Label to "Which Times Table do you want?"
  • Now double click your new button to get at the code window. Add the following code:
Dim numbers(10) As Integer
Dim times As Integer
Dim StoreAnswer As Integer
Dim i As Integer
ListBox1.Items.Clear()
times = Val(TextBox1.Text)
For i = 1 To 10
StoreAnswer = i * times
numbers(i) = StoreAnswer
ListBox1.Items.Add(times & " times " & i & " = " & numbers(i))
Next i
Run the programme. Enter a number in your new text box, and then click the Times Table Arraybutton. The times table for the number should have been printed.

  At the top of the code we set up three normal Integer variables, i, times and StoreAnswer. (We didn't really need the StoreAnswer variable, but it is here to make the code more readable.) We also set up an array. (Notice that we set it to 10. This actually gives us 11 positions in the array. But we're only putting something in positions 1 to 10. This is because it is more convenient for us, and for our Loop.)
Dim numbers(10) As Integer
We need to know what number we are going to be multiplying by, which times table we're working out. We get this number from the Textbox, and can assign it directly to the variable times
times = Val(Textbox1.Text)
We can then set up a For Loop. Inside the For Loop is where we'll assign values to each position of our array:
numbers(i) = StoreAnswer
First time around the loop, the variable i will hold a value of 1. So the second position of our array,numbers(1) will be assigned whatever is in the variable StoreAnswer
The second time around the loop, the variable will hold a value of 2. So the second position of our array, numbers(2), will again be assigned whatever is in the variable StoreAnswer
We go round and round the loop assigning values to all ten positions of our array.
The other two lines of code inside the array just work out the times tables, and Adds the answer to the List Box. Study them, and make sure you understand how they work.
But the point of this is to demonstrate that you can use code to assign a value to a position in an array.
In the next part, we'll take a look at situations where you don't know how many items will be in an array.

Arrays where the Boundaries are not known


Study the following Form:



In the above Form, the user is invited to enter values into three Textboxes. The first Textbox is for whatever times table he or she wants. The second Textbox asks for the starting value of the times table. The third Textbox is for the end number of the times table. In other words, 1 times 4, 2 times 4, 3 times 4, right up to 12 times 4.
The point is that the user can enter any values he or she wants. We won't know until they are entered, and the button is clicked. Up until now, we've used an array with a fixed size. Our previous times table programme only went up to 10, and it started at 1. We used this to set up our array:
Dim numbers(10) As Integer
But that array would be no good for the above Form. Our array only held 11 positions. The user definitely wants the 4 times table right up to 12. Is there any way we can set up an array where the number of positions is not known? How can we set up a Non-Fixed size array?
You do it like this. First set up an array with empty brackets
Dim numbers( ) As Integer
Next, pass the values from the Text Boxes to some variables
times = Val(Textbox1.Text)
startAt = Val(Textbox2.Text)
endAt = Val(Textbox3.Text)
We can then use these values to reset the array. You reset an array by using the ReDim word. You then specify the new values. Like this:
ReDim numbers(endAt)
Our original array did not have its size set - Dim numbers( ) As Integer. So we've got the end number from the Textbox. When we reset an array, we can use this new value. Since our user entered the value 12 for the end number, our array is now really this:
Dim numbers(12) As Integer
We can use the same variables for our For Loop. Then we can go round and round the loop assigning values to our array.

Dim numbers() As Integer
Dim startAt As Integer
Dim endAt As Integer
Dim times As Integer
Dim StoreAnswer As Integer
Dim i As Integer
times = Val(TextBox1.Text)
startAt = Val(TextBox2.Text)
endAt = Val(TextBox3.Text)
ReDim numbers(endAt)
For i = startAt To endAt
StoreAnswer = i * times
numbers(i) = StoreAnswer
ListBox1.Items.Add(times & " times " & i & " = " & numbers(i))
Next i
When you're finished, run your programme and test it out. Click the button and the times table should appear in the List Box.

And that is how to set up an array when you don't know what size the array is going to be - set up an array with empty brackets. Reset the array with the ReDim word, and then give it some new values.
Arrays can be a very tricky subject, and they dp take some getting used to. But they are well worth your time and effort - they'll make your coding life a lot easier!
We'll move on to another subject - working with Strings of text.

String Manipulation in VB .NET

Humans are far from perfect. Especially when they are entering data into textboxes! Sometimes they won't enter any details at all in the boxes you want them to. And then when they do enter something, they often get it wrong. Sometimes on purpose, just to trip you up. By manipulating Strings of data, we can check things like text in a textbox to see if it is correct, and thereby gain some control of the user's actions.

First, let's take a closer look at the String variable type.

The String Variable Type

There's more to the string variable type than meets the eye. You've used them a lot to store text. But the string variable types come with a lot of inbuilt power. Strings have their own properties and methods, just like a textbox or label or form does. That's because strings are objects. (In fact, all variables are objects in VB.NET, including the number variables.) In a later section, we'll be going into a bit more detail on objects. For now, think of them as things that can be manipulate - Like the textbox, label and form just mentioned.

And strings variables can be directly manipulated, too. An example should clear things up.

  • Start a new project.
  • Add two textboxes and a button to your new form.
  • For Textbox1, set the Text property to “string variables”.
  • Double click the button to open the coding window.
  • Type the following as the code for the button:

Dim strUpper As String

strUpper = TextBox1.Text
TextBox2.Text = strUpper.ToUpper( )

Run your code and see what happens when you click the button.

You should have found that the text from Textbox1 gets converted to uppercase letters.

The reason it gets converted is because we used the ToUpper method of the string variable. When you typed the full stop after the variable name, you probably saw this pop up box:

StringMethods

Simply double click the method you want, and it's added to your code.

strUpper.ToUpper( )

Notice that the name of the variable you want to do something with comes first. Then, after the full stop, you add the name of the method.

It's easy to guess what some of the methods do (like ToLower), but others are a bit more enigmatic (Like Substring).

In this section, we'll go through some of the string methods to see what they do, and how useful they can be in your code.

Length and Chars on that list above are properties, and not methods. We'll be using these two, and they come in quite useful.

 

Manipulating data from a Text Box

You already know how to pass data from a Textbox into a variable. Just do this

Dim FirstName As String

FirstName = txtFirst.Text

Then whatever was in the Textbox you called txtFirst will get transferred directly to the String variable you set up. Once the data is in the variable, you can test it to see if it's the type of data you want. After all, the user could have entered numbers to try and trip you up. Or they could have left it blank.

  • Add a new textbox to your form
  • Change the Name property to txtFirst
  • Add a second button to your form
  • Set the Text property to whatever you want
  • Double click the button and add the following code:

Dim FirstName As String

FirstName = txtFirst.Text

If FirstName = "" Then

MsgBox "Please enter your First Name in the text box"
Exit Sub

End If

In this code, we are passing whatever is in the text box directly to the variable called FirstName. We are then testing what is inside the variable with an If statement. We want to test if the user has actually entered something into the text box. If they've left it blank, we want to tell them to try again. We also want to exit the Subroutine. After all, if they got it wrong, we don't want to proceed with any code we might have written.

The way we are testing to see if the user has left the text box blank is this:

If FirstName = "" Then

We've put two sets of double quotes together. This signifies a string of text that is blank. If the user didn't enter anything at all, then our variable FirstName will contain a blank string. This is what we're testing for.

Run the programme and try it out. Don't type anything at all in the textbox, but just click the button. The message box should display.

Now, click inside the textbox. Hit the space bar three times. And then click the button. Did the Message box display?

So why didn't it? After all, there was nothing in the textbox. Isn't that an blank string? What was passed to the variable?

Well, when you press the space bar Visual Basic counts that as a text character. So when you press the space bar three times what is in the variable is this:

FirstName = " "

and not this:

FirstName = ""

The two are entirely different, according to Visual Basic. After all, you might have wanted three spaces!

So how can we check to see if there is anything at all in our textbox? How do we defeat the user who has tried to fool us by hitting the space bar a number of times?

In the rest if this section, you'll learn about the various ways you can use the String methods and properties to examine what a particular string contains. First up is the Trim method.

The Trim Method in VB .NET

In the previous part you added code to transfer some text that was in a Textbox over to a variable. The code you wrote was this:

Dim FirstName As String

FirstName = txtFirst.Text

If FirstName = "" Then

MsgBox "Please enter your First Name in the text box"
Exit Sub

End If

But the user could press the spacebar in your textbox. Although there would be no letters or numbers inthe textbox, the above error checking wouldn't work - all of the blank spaces would get passed to your variable. We can use a String method called Trim to solve this problem.

 

The Trim Method

One of the methods on our list was Trim. What this does is to trim any leading or trailing blank spaces from a string. So if the string was " Text", then Trim would delete those spaces for you, leaving just"Text".

You use it in your code. Like this:

FirstName = txtFirst.Text
FirstName = FirstName.
Trim

First, we put the text from the textbox into a variable called FirstName. Then we said "assign to the variable FirstName (FirstName = ) the value of FirstName trimmed (FirstName.Trim)".

Again, though, we're just adding the method we want after the variable name. VB will take care of the trimming for us.

Another way to Trim is to use the Trim() function directly. Like this:

FirstName = Trim( txtFirst.Text )

What you are trimming here is any blank spaces from around text entered directly in the text box called txtFirst

But we now have a way to thwart that user who is trying to trip us up by entering blank spaces into our text box. If you were programming a Form where the First Name was going into a database, then it's essential you trap anything like this.

OK, we've tested to see if the First Name text box was empty. Is there anything else we can do? What if our clever-clogs user tries to fool us again. This time he (they're always "he's"!) decides to enter some numbers. He claims his name is "George12345". Is there anything we can do to stop his little games? Is there a way to test that the data entered into a text box was text and not numbers?

Indeed there is! We'll use the Chars Property to see if we can check for numbers and text. You'll also see the difference between Chars and Char.

Char and Chars in VB .NET

Char ( NOT Chars)

Char is a variable type. It can hold one character at a time (the Char is short for Character). You set it up like this:

Dim OneCharacter As Char

You can then store a character in the variable like this:

OneCharacter = "A"

Or like this:

Dim OneCharacter As Char = "a"

You can even do this:

Dim OneCharacter As Char = "apple"

But if you try to put a whole word into a Char variable, only the first letter will be retained.

So what good is the Char variable type?

Well, a common use for it is to transfer one letter at a time from a string, and then test to see what this character is. You can test to see if it's a number, for example. Or perhaps to test if the string contains an "@" symbol for a valid email address. We'll test for a number. In the process, we can study the Length property of string variables.

Add another textbox and a button to your form from the first part of the tutorial. Change the Nameproperty of the textbox to txtChars. For the Text property of the Textbox, enter "George123". Double click the new button and enter the following variable declarations:

Dim OneCharacter As Char
Dim FirstName As String
Dim i As Integer
Dim TextLength As Integer

Remember what we're going to be doing here. We're going to put the text from the textbox into a string variable. Then we'll loop round every character in the string to see if it's a number.

So the next line to add to your code is the one that transfers the text from the textbox to the string variable. Add this:

FirstName = Trim(txtChars.Text)

The next thing we need is the length of the string. We need this for the end value of our loop. The length property will give us this answer. So add this line:

TextLength = FirstName.Length

The length property of a string variable tells you how many characters are in the string. You can add a message box to test out your code so far:

MsgBox("Number of characters is: " & TextLength)

Run your programme. Click the button and test out your code. You should see a message box popping up like this one:

Charmsgbox

So we've found out that "George123" has 9 characters.

We can now loop round each character in the string and test which ones are the numbers. Add the following For loop to your code (you can delete or comment out your message box line now):

For i = 0 To TextLength - 1

Next i

So the For loop starts at zero and ends at the length of the text, minus 1. (It will loop from 0 to 8 in our code - 9 characters. We'll see why you have to deduct 1 soon.

Inside of our loop, we need to grab one character at a time, and then put it into our Char variable. You can do that with the Chars() Property of the string variable type.

 

Chars (NOT Char)

Chars is a method of the String variable type. You can use it on any length of string, not just a Char variable. And that's the difference between the two: Char is a variable type, while Chars is a method you can use on Strings.

Chars works like this:

OneCharacter = FirstName.Chars(i)

You type the name of your variable, then after the full stop you add Chars(). Inside of the round brackets, you need a number. This number is the position in the string you want to grab. So if you wanted the third letter of a string variable, you'd put this:

Dim SomeString As String
Dim OneCharacter As Char

SomeString = "George123"
OneCharacter = SomeString.Chars(2)

The variable OneCharacter would then hold the third letter - "o".

The reason we've put 2 inside of the round brackets and not 3 is because VB starts counting the characters from zero, and NOT 1. And that's why our For Loop is this:

For i = 0 To TextLength - 1

You have to deduct 1 because the Chars() count starts at zero.

So amend your For Loop to this:

For i = 0 To TextLength - 1

OneCharacter = FirstName.Chars(i)
MsgBox(OneCharacter)

Next i

Run your code, and then click your button. You should get a message box displaying. In fact, you'll get 9 message boxes, one for each character in the string!

Ok, try these exercises to test your new knowledge.

Exercise

Add an If statement to your For Loop. Check each character of the string "George123". If you find a number, display a suitable message, something like "A number was found". Exit the for loop when the first number is found.

To check if a variable is a number, you can use the IsNumeric( ) function. This function will return either True or False. In other words, if the variable being checked is a number, then IsNumeric( ) is True; if IsNumeric( ) is not a number then False gets returned.

If IsNumeric(OneCharacter) Then


Exercise

Amend your code to keep a count of how many characters in the string are numbers. Display the count in a message box.

In the next part, we'll take a look at another useful String method - InStr.

The InStr() Method in VB .NET

String Position

The InStr( ) method of string variables tells you what the position of one string is inside another. For example, if your string was "me@me.com" and you wanted to know if the string contained the @symbol, you could use InStr( ) Method. You would use it like this

FirstString = "me@me.com"
SecondString = "@"

position = InStr( FirstString, SecondString )

The variable FirstString is the string we want to search; SecondString is what we want to search for. You can specify a starting position for the search to begin. If you do, this number goes at the start (the default is zero):

position = InStr( 1, FirstString, SecondString )

The variable called position has to be an integer variable. That's because the InStr() Method returns a number, and not text. In the code above, position would have a value of 3. That's because the @ symbols starts at the third letter of "me@me.com".

(Note: the InStr() Method starts counting at 1, and not zero like Chars(), which is very confusing!)

If the string you're searching for is not found, then the value placed inside of your integer variable (position in our case) is zero. That enables you to code something like this:

If position = 0 Then

MsgBox "Not a Valid email address: There was No @ Sign"

End If

 

Another useful string method is Substring. We'll see how to use it in the next part.

The Substring() Method in VB .NET

Substring

Another useful string method is Substring. This allows you to grab one string within another. (For example, if you wanted to grab the ".com" from the email address "me@me.com")

In between the round brackets of Substring( ), you specify a starting position, and then how many characters you want to grab (the count starts at zero again). Like this:

Dim Email as String
Dim DotCom as String

Email = "me@me.com"
DotCom = Email.Substring( 5, 4 
)

MsgBox(DotCom)

The message box would then display the characters grabbed from the string, in this case the ".com" at the end (start at position 5 in the string and grab 4 characters).

You could also do a check to see if an email address ended in ".com" like this:

Dim Email As String
Dim DotCom As String

Email = "me@me.con"
DotCom = Email.Substring( Email.Length - 4, 4 
)

If DotCom = ".com" Then

MsgBox("Ends in Dot Com")

Else

MsgBox("Doesn't End in Dot Com")

End If

The starting position for Substring( ) this time is "Email.Length - 4". This is the length of the string variable called Email, minus 4 characters. The other 4 means "grab four characters"

You have to be careful, though. If there wasn't four characters to grab, VB would give you an error message.

We could replace the Chars() For loop code we wrote earlier with a Substring() method. The result would be the same. Here's the code:

For i = 0 To TextLength - 1

OneCharacter = FirstName.Substring( i, 1 )
MsgBox OneCharacter

Next i

So we're saying, "Start grabbing characters from the position i. Just grab one character".

Substring and Chars are very useful methods to use when you want to check the letters in a string of text.

In the next part, we'll take a look at the Equals, Replace, and Insert Methods.

Equals, Replace, and Insert Methods

The Equals Method

In code previously, we had this:

If DotCom = ".com" Then

MsgBox("Ends in Dot Com")

Else

MsgBox("Doesn't End in Dot Com")

End If

You can use the Equals method of string variables in the first line, instead of an equals ( = ) sign:

If DotCom.Equals( ".com" ) Then

So after the name of your string variable comes the full stop. Then select "Equals" from the popup list. In between the round brackets, you type the string (or variable name) that you want VB to compare.

The Equals method is used to compare one string of text against another. If they're the same a value of True is returned, else it's False.

 

The Replace Method

You can replace text in one string with some other text. The process is fairly straightforward. Here's some code that uses replace. Add a button to a form and test it out:

Dim OldText As String
Dim NewText As String

OldText = "This is some test"
NewText = OldText.Replace( "test", "text" 
)

MsgBox( OldText )
MsgBox( NewTex t)

When you run the programme, the first message box will say "This is some test" and the second box will say "This is some text".

The text you want to get rid of comes first. Then after a comma, type the new text. You can use string variables rather than direct text surrounded by double quotes, for example:

Dim NewWord As String = "Text"
NewText = OldText.Replace( "test", NewWord 
)

 

The Insert Method

You can also insert some new text into an string. Here's some code to try out:

Dim SomeText As String
Dim NewText As String

SomeText = "This some text"
NewText = SomeText.Insert( 5, "is " 
)

MsgBox( SomeText )
MsgBox( NewText )

The 5 in round brackets means start at position 5 in the string variable SomeText (the count starts at zero). You then type the text that you want inserted. You can use a variable name instead of direct text surrounded by quotes.

In the next part, we'll take a look at how to use Split() and Join in VB .NET.

Text Files and VB .NET

There is a very useful object in VB.NET called System.IO (the IO stands for Input and Output). You can use this object to read and write to text files.

We're going to be having a closer look at objects (and what System is) in the next section. For now, let's just see how to open up a text file using the System.IO object.

First, here's an explanation of just what we mean by "text file".

What is a Text File?

The files on your computer all end in a three letter extensions. Microsoft Word files will have a different three letter extension from Microsoft Excel files. The extension is used to identify one file type from another. That way, Excel won't try to open Word files, or vice versa. You can just write some code to strip the last three letters from the file name, and then check that these three letters are the ones you want. Rather like the code you wrote to strip the last three letters from an email address.

Text files have an extension that ends in .txt. The Windows operating system gives you a good, basic Text Editor in Notepad. The Notepad programme allows you to save files with the .txt extension. In other words, as Text Files. These Text Files can then be opened by a wide variety of programmes.

A simple text file like this is called a Sequential File, and that is what we will be opening here. So let's begin.

How to Open a Text File in VB .NET

The ability to open up a text file and read its contents can be very useful to you in your programming life. You might have a text file containing quiz questions and answers, for example. You could read the questions and answers from a text file and create your own "Who wants to be a Millionaire" game. Or you might want to save some data associated with your programme, and then open it up again when the programme starts. Well see how to open up a text file in VB .NET right now. In a later section, you'll learn how to save data to a text file.

 

To open up a text file, you need to create something called a "StreamReader". This, as its name suggests, reads streams of text. The StreamReader is an object available to System.IO. You create a StreamReader like this (if you have Windows XP, you can just use C:\test.txt instead of the longer file name we use for these text file tutorials):

Dim FILE_NAME As String = "C:\Users\Owner\Documents\test.txt"

Dim objReader As New System.IO.StreamReader( FILE_NAME )

The first line just sets up a string variable called FILE_NAME. We store the path and name of our text file inside of the string variable:

= "C:\Users\Owner\Documents\test.txt"

We're saying that there is a text file called test which is at the location (path) "C:\".

You set up the StreamReader to be a variable, just like a String or Integer variable. But we're setting up this variable differently:

Dim objReader As New System.IO.StreamReader( FILE_NAME )

We've called the variable objReader. Then, after the "As" word comes "New". This means "Create a New Object". The type of object we want to create is a StreamReader object:

System.IO.StreamReader

Sysytem is the main object. IO is an object within System. And StreamReader is an object within IO.

StreamReader needs the name of a file to Read. This goes between a pair of round brackets:

System.IO.StreamReader( FILE_NAME )

VB will then assign all of this to the variable called objReader. So instead of assigning say 10 to an Integer variable, you are assigning a StreamReader to a variable.

Read To End

But this won't do you any good. We haven't actually opened the text file yet. We've just told VB where the text file is and what object to open it with. You do the opening like this:

TextBox1.Text = objReader.ReadToEnd

Now that objReader is an object variable, it has its own properties and methods available for use (in the same way that the textbox has a Text property).

One of the Methods available to our new StreamReader variable is the ReadToEnd method. This will read the whole of your text, right to the end. We're then popping this in a textbox.

Let's test all this theory out. Do the following:

  • Start a new project
  • Add a textbox to your new form, and just leave it on the default Name of Textbox1
  • Set its MultiLine property to True
  • Add a Button to your form
  • Double click the button and add the following code for it:

Dim FILE_NAME As String = "C:\Users\Owner\Documents\test.txt"

Dim objReader As New System.IO.StreamReader( FILE_NAME )

TextBox1.Text = objReader.ReadToEnd

objReader.Close()

The last line closes the StreamReader we set up. You have to close your stream objects after you’ve used them, otherwise you’ll get errors messages.

When you’re done, run your programme and click your Button.

Unless you already have a file called test.txt at the location specified you’ll get this error message popping up:

FileNotFound

The last line spells it out clearly: Could not find file "C:\Users\Owner\Documents\test.txt". So we were trying to read a text file that doesn't exist.

Does the File Exist?

You can, though, test to see if the file exists. If it does, you can open it; if not, you can display an error message. Amend your code to this (the new lines are in bold):

Dim FILE_NAME As String = "C:\Users\Owner\Documents\test.txt"

If System.IO.File.Exists(FILE_NAME) = True Then

Dim objReader As New System.IO.StreamReader(FILE_NAME)
TextBox1.Text = objReader.ReadToEnd
objReader.Close()

Else

MsgBox("File Does Not Exist")

End If>

We've now wrapped up our code in an If Statement. The first line of the If Statement is this:

If System.IO.File.Exists( FILE_NAME ) = True Then

This tests to see whether or not a file exists. Again, you start with System.IO. Then you access another object of System.IO - the File object. This has a method called Exists. In between the round brackets, you type the name (or variable) of the file you want to check. The value returned will either be True (if it does exists), or False (if it doesn't).

If the file exist then we can go ahead and create our StreamReader; If it doesn't, we can display a error message for the user.

So that your programme will work, there is a file below called "test.txt". Download this to your computer, either in the main C:\ folder for XP users, or the Documents folder if you have Vista/Windows7. (Right click the file and select Save Target As (IE), or Save Links As (Firefox):

Create your own text file

hereWhen you have done that, run your programme again. Click the button once more, and you should see the text from your file appear in the textbox. (If you get the error message again, it means you haven't copied the file to the right place.)

In the next part, we'll see how to read the contents line by line, instead of all in one go.

Reading a Text File Line by Line

Quite often, you don't want to read the whole file at once. You want to read it line by line. In which case, instead of using the ReadToEnd method, as we did in the previous section, you can use theReadLine method:

The ReadLine method, as its name suggests, reads text one line at a time. In order to do this, though, you need to use a loop. You can then loop round each line and read it into a variable. Here's a coding example:

Dim TextLine As String

Do While objReader.Peek() <> -1

TextLine = TextLine & objReader.ReadLine() & vbNewLine

Loop

The first line of the Do While loop is rather curious:

Do While objReader.Peek() <> -1

The Peek method takes a peek at the incoming text characters. It's looking ahead one character at a time. If it doesn't see any more characters, it will return a value of minus 1. This will signify the end of the text file. Our loop checks for this minus 1, and bails out when Peek has this value.

Inside the loop, we're reading each line from the text file and putting into new variable. (We're also adding a new line character on the end. Delete the & vbNewLine and see what happens).

objReader.ReadLine()

So the ReadLine method reads each line for you, instead of the ReadToEnd method which gets the whole of the text file.

Once you have a line of text in your variable, though, it's up to you to parse it. For example, suppose the line of text coming in from the text file was this:

"UserName1, Password1, UserName2, Password2"

You would then have to chop the line down and do something which each segment. VB won't do this for you! (But you saw how to do this in the last section, when you used things like Substring.)

But what you are doing in the Do Loop is building up your variable with lines of text that are pulled from your text file. Once you have pulled all the text from your file, you can then put it into the text box. Here's our programme once more, with the new code highlighted in bold text:

Dim FILE_NAME As String = "C:\Users\Owner\Documents\test.txt"

Dim TextLine As String

If System.IO.File.Exists( FILE_NAME ) = True Then

Dim objReader As New System.IO.StreamReader(FILE_NAME)

Do While objReader.Peek() <> -1

TextLine = TextLine & objReader.ReadLine() & vbNewLine

Loop

Textbox1.Text = TextLine

Else

MsgBox("File Does Not Exist")

End If

So inside the loop, we go round building up the TextLine variable. Once all the file has been read (when Peek() has a value of -1), we then place it into Textbox1. 

In the next part, you'll learn how to write to a text file.

How to Write to a Text File in VB .NET

Writing to a text file is similar to reading a text file. Again we use System.IO. This time, instead of using the StreamReader we use the StreamWriter. The StreamWriter is used to write a stream of text to a file.

Add another Button to the form you've been working on. Set the Text property of the button to "Write to File". Double click your new button to open up the coding window. Add the following:

Dim FILE_NAME As String = "C:\Users\Owner\Documents\test2.txt"

If System.IO.File.Exists(FILE_NAME) = True Then

Dim objWriter As New System.IO.StreamWriter( FILE_NAME )

objWriter.Write( TextBox1.Text )
objWriter.Close()
MsgBox("Text written to file")

Else

MsgBox("File Does Not Exist")

End If

Run your programme, and then click your new button.

Unless you have a file called "test2.txt", you should see the message box display: "File Does Not Exist."

Once again, VB insists that the file must exist before it can actually do something with it. Which is not unreasonable!

Stop your programme and change this line:

Dim FILE_NAME As String = "C:\Users\Owner\Documents\test2.txt"

To this:

Dim FILE_NAME As String = "C:\Users\Owner\Documents\test.txt"

In other words, just change the file name back to test.txt. (Hopefully, you haven't deleted the test.txt file from your hard drive!)

Run your programme again. Type something into the textbox, and then click your button. You should see the message box "Text written to file" appear.

But notice that if you open up the text file itself, any text you had previously will be gone - it has been overwritten, rather than appended to. (We'll see how to append text to a file shortly.)

Let's have a look at the code we wrote, though.

Once again, we check to see if the File Exists. If it's True that the file exists, then the first line that gets executed is setting up our variable:

Dim objWriter As New System.IO.StreamWriter(FILE_NAME)

It's almost the same as last time. Only two things have changed: we created a new variable name,objWriter, and we're now using StreamWriter instead of StreamReader. Everything else is the same.

To write the text to our file, we've used this:

objWriter.Write( TextBox1.Text )

After the name of our variable (objWriter), we typed a full stop. The drop down box appeared showing available properties and methods. The "Write" method was chosen from the list. In between round brackets, you put what it is you want VB to write to your text file. In our case, this was the text inTextbox1. You can also do this:

objWriter.Write( "Your Text Here" )

The above uses direct text surrounded by double quotes. This is also acceptable:

Dim TheText As String = "Your Text Here"

objWriter.Write( TheText )

This time, we've put the text inside of a variable. The name of the variable is then typed inside of the round brackets of "Write".

But you don't have to write the whole text at once. You can write line by line. In which case, selectWriteLine from the available properties and methods. Here's an example of how to use WriteLine:

Dim FILE_NAME As String = "C:\Users\Owner\Documents\test.txt"
Dim i As Integer
Dim aryText(4) As String

aryText(0) = "Mary WriteLine"
aryText(1) = "Had"
aryText(2) = "A"
aryText(3) = "Little"
aryText(4) = "One"

Dim objWriter As New System.IO.StreamWriter( FILE_NAME )

For i = 0 To 4

objWriter.WriteLine( aryText(i) )

Next

objWriter.Close()

The error checking code has been left out here. But notice the new way to write text to the file:

objWriter.WriteLine( aryText(i) )

We're looping round and writing the contents of an array. Each line of text from the array gets written to our text file. But each line is appended. That is, the text file doesn't get erased after each line has been written. All the lines from the array will be written to the text file. However, if you were to run the code a second time then the contents of the file are erased before the new WriteLine() springs into action. In other words, you'd only get one version of "Mary WriteLine had a little one" instead of two.

In the next part we'll see how to add text to a file that already contains text - called appending to a file.