Microsoft Visual Basic 2010 Step by Step eBook

(Tina Meador) #1

306 Part II Programming Fundamentals


This statement creates a new collection and assigns it the variable name URLsVisited.
Because you’re placing the declaration in the declaration area for the form, the
collection has scope throughout all the form’s event procedures.


  1. Display the form again, double-click the Visit Site button, and then type the following
    code in the Button1_Click event procedure:


URLsVisited.Add(TextBox1.Text)
System.Diagnostics.Process.Start(TextBox1.Text)
This program code uses the Add method to fill up, or populate, the collection with
members. When the user clicks the Button1 object, the program assumes that a valid
Internet address has been placed in the TextBox1 object. Every time the Button1
object is clicked, the current URL in TextBox1 is copied to the URLsVisited collection
as a string. Next, the System.Diagnostics.Process.Start method is called with the URL
as a parameter. Because the parameter is a URL, the Start method attempts to open
the URL by using the default Web browser on the system. (If the URL is invalid or
an Internet connection cannot be established, the Web browser handles the error .)

Note The only URLs that this program adds to the URLsVisited collection are those you’ve
specified in the TextBox1 object. If you browse to additional Web sites by using your Web
browser, those sites won’t be added to the collection.


  1. Display the form again, and then double-click the List Recent Sites button.

  2. Type the following program code using the Code Editor:


Dim URLName As String = "", AllURLs As String = ""
For Each URLName In URLsVisited
AllURLs = AllURLs & URLName & vbCrLf
Next URLName
MsgBox(AllURLs, MsgBoxStyle.Information, "Web sites visited")
This event procedure prints the entire collection by using a For Each... Next loop and a
MsgBox function. The routine declares a string variable named URLName to hold each
member of the collection as it’s processed and initializes the variable to empty (“”). The
value is added to a string named AllURLs by using the concatenation operator (&), and
the vbCrLf string constant is used to place each URL on its own line.
Finally, the AllURLs string, which represents the entire contents of the URLsVisited
collection, is displayed in a message box. I added the MsgBoxStyle.Information
argument in the MsgBox function to emphasize that the text being displayed is general
information and not a warning. (MsgBoxStyle.Information is also a built-in Visual Basic
constant .)


  1. Click the Save All button to save your changes. Specify the C:\Vb10sbs\Chap12 folder as
    the location.

Free download pdf