Creating Your Own Collections


Creating Your Own Collections

With Visual Basic, you can also create your own collections to track data in a program and manipulate it systematically. Although collections are often created to hold objects, such as user interface controls, you can also use collections to store numeric or string values while a program is running. In this way, collections nicely complement the capabilities of arrays, which you learned about in the last chapter.

Declaring New Collections

New collections are declared as variables in a program, and the location in which you declare them determines their scope, or the extent to which their assigned values persist. Because collections are so useful, I usually declare them at the top of a form or in a module.

New collection declarations require the syntax

Dim CollectionName As New Collection()

where CollectionName is the name of your collection. If you place the collection declaration in a module, you use the Public keyword instead of the Dim keyword. After you create a collection, you can add members to it by using the Add method, and you can examine the individual members by using a For Each…Next loop.

The following exercise shows you how to create a collection that holds string data representing the Internet addresses (Uniform Resource Locators, or URLs) you've recently used while surfing the Web. To connect to the Web, the program will use the Visual Basic System. Diagnostics.Process.Start method and your default Web browser, a technique that I first introduced in Chapter 3, “Working with Toolbox Controls.”

Track Internet addresses by using a new collection

  1. Click the Close Project command on the File menu.

  2. Create a new project named My URL Collection.

  3. Draw a wide text box object at the top of the form, centered within the form.

  4. Draw two wide button objects below the text box object on the form, one button below the other.

  5. Set the following properties for the form and its objects:

    Object

    Property

    Setting

    TextBox1

    Text

    “http://www.microsoft.com/learning/books/”

    Button1

    Text

    “Visit Site”

    Button2

    Text

    “List Recent Sites”

    Form1

    Text

    “URL Collection”

  6. Your form looks like this:

    graphic

  7. Click the View Code button in Solution Explorer to display the Code Editor.

  8. Move the insertion point at near the top of the form's program code, and directly below the statement Public Class Form1, type the following variable declaration, and then press Enter:

    Dim URLsVisited As New Collection()

    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 of the form's event procedures.

  9. 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 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.

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

  11. 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.)

  12. Click the Save All button to save your changes. Specify the c:\vb05sbs\chap12 folder as the location.

    NOTE
    To run the URL Collection program, your computer must establish a connection to the Internet and be equipped with a Web browser, such as Microsoft Internet Explorer or Netscape Navigator.

Run the URL Collection program

TIP
The complete URL Collection program is located in the c:\vb05sbs\chap12\url collection folder.

  1. Click the Start Debugging button to run the program.

    The program displays a default Web site in the URL box, so it isn't necessary to type your own Internet address at first.

  2. Click the Visit Site button.

    Visual Basic adds the Microsoft Press Web site (http://www.microsoft.com/learning/books/) to the URLsVisited collection, opens the default Web browser on your system, and loads the requested Web page, as shown here. (You can explore the Web site if you're interested.)

    graphic

  3. Click the form again. (You might need to click the form's icon on the Windows taskbar.)

  4. Click the List Recent Sites button.

    Visual Basic executes the event procedure for the Button2 object. You see a message box that looks like this:

    graphic

  5. Click OK in the message box, type a different Web site in the form's text box, and then click the Visit Site button.

    You might want to visit the Microsoft Visual Basic Developer Center site located at msdn.microsoft.com/vbasic/ to learn more about Visual Basic.

  6. Visit a few more Web sites by using the URL Collection form, and then click the List Recent Sites button.

    Each time you click List Recent Sites, the MsgBox function expands to show the growing URL history list, as shown here:

    graphic

    If you visit more than a few dozen Web sites, you'll need to replace the MsgBox function with a multiline text box on the form. (Can you figure out how to write the code?)

  7. When you're finished, click the Close button on the form, and then close your Web browser.

Congratulations! You've learned how to use the Controls collection and how to process collections by using a For Each…Next loop. These skills will be useful whenever you work with collections in the System.Collections namespace. As you become more familiar with classic computer science data structures and algorithms related to list management (stacks, queues, dictionaries, hash tables, and other structured lists), you'll find that System.Collections provides Visual Studio equivalents to help you manage information in extremely innovative ways. (For a few book ideas related to data structures and algorithms, see “General Books about Programming and Computer Science” in Appendix A.)



Microsoft Visual Basic 2005 Step by Step
Microsoft Visual Basic 2005 Step by Step (Step by Step (Microsoft))
ISBN: B003E7EV06
EAN: N/A
Year: 2003
Pages: 168

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net