Click here to Skip to main content
15,353,818 members
Articles / Programming Languages / Visual Basic
Posted 17 Feb 2004


19 bookmarked

Sams Teach Yourself Microsoft Visual Basic .NET 2003 in 24 Hours Complete Starter Kit Chapter 3: Understanding Objects and Collections

Rate me:
Please Sign up or sign in to vote.
4.00/5 (3 votes)
17 Feb 200434 min read
Understanding Objects and Collections in VB.NET.
Sample Image - 0672325373c.jpg
AuthorJames Foxall
Title Sams Teach Yourself Microsoft Visual Basic .NET 2003 in 24 Hours Complete Starter Kit
PublishedJUN 06, 2003
ISBN 0672325373
PriceUS$ 29.99

Understanding Objects and Collections

In Hour 1, "Jumping In with Both Feet: A Visual Basic .NET Programming Tour", you were introduced to programming in Visual Basic .NET by building a Picture Viewer project. You spent the previous hour digging into the integrated development environment (IDE) and learning skills critical to your success with Visual Basic .NET. In this hour, you're going to start learning about some important programming concepts, namely objects.

The term object as it relates to programming might have been new to you prior to this book. The more you work with Visual Basic .NET, the more you'll hear about objects. Visual Basic .NET, unlike its predecessors, is a true object-oriented language. This hour isn't going to discuss object-oriented programming in any detail—object-oriented programming is a very complex subject and well beyond the scope of this book. Instead, you'll learn about objects in a more general sense.

Everything you use in Visual Basic .NET is an object, so understanding this material is critical to your success with Visual Basic .NET. For example, forms are objects, as are the controls you place on a form; pretty much every element of a Visual Basic .NET project is an object and belongs to a collection of objects. All objects have attributes (called properties), most have methods, and many have events. Whether creating simple applications or building large-scale enterprise solutions, you must understand what an object is and how it works. In this hour, you'll learn what makes an object an object, and you'll also learn about collections.

The highlights of this hour include the following:

Note - If you've listened to the programming press at all, you've probably heard the term object oriented, and perhaps words such as polymorphism, encapsulation, and inheritance. In truth, these new object-oriented features of Visual Basic are very exciting, but they're far beyond Hour 3 (or Hour 24, for that matter). You'll learn a little about object-oriented programming in this book, but if you're really interested in taking your programming skills to the next level, you should buy a book dedicated to the subject after you've completed this one.

Understanding Objects

Object-oriented programming has been a technical buzzword for quite some time, but as far as Visual Basic programmers are concerned, it became a reality only with Visual Basic .NET (no previous version of Visual Basic was a true OO language). Almost everywhere you look—the Web, publications, books—you read about objects. What exactly is an object? Strictly speaking, an object is a programming structure that encapsulates data and functionality as a single unit and for which the only public access is through the programming structure's interfaces (properties, methods, and events). In reality, the answer to this question can be somewhat ambiguous because there are so many types of objects—and the number grows almost daily. However, all objects share specific characteristics, such as properties and methods.

The most commonly used objects in Visual Basic .NET are the form object and the control object. Earlier hours introduced you to working with forms and controls and even showed you how to set form and control properties. In your Picture Viewer project from Hour 1, for instance, you added a picture box and two buttons to a form. Both the PictureBox and the Button controls are control objects, but each is a specific type of control object. Another, less-technical example uses pets. Dogs and cats are definitely different entities (objects), but they both fit into the category of Pet objects. Similarly, text boxes and buttons are each a unique type of object, but they're both considered a control object. This small distinction is important.

Understanding Properties

All objects have attributes used to specify and return the state of the object. These attributes are properties, and you've already used some of them in previous hours using the Properties window. Indeed, every object exposes a specific set of properties, but not every object exposes the same set of properties. To illustrate this point, I'll continue with the hypothetical Pet object. Suppose that you have an object, and the object is a dog. This Dog object has a certain properties that are common to all dogs. These properties include attributes such as the dog's name, the color of its hair, and even the number of legs it has. All dogs have these same properties; however, different dogs have different values for these properties. Figure 3.1 illustrates such a Dog object and its properties.

Image 2

Figure 3.1

Properties are the attributes that describe an object.

Getting and Setting Properties

You've already seen how to read and change properties using the Properties window. The Properties window is available only at design time, however, and is used only for manipulating the properties of forms and controls. Most getting and changing of properties you'll perform will be done with Visual Basic .NET code, not by using the Properties window. When referencing properties in code, you specify the name of the object first, followed by a period (.), and then the property name, as in the following syntax:


If you had a Dog object named Bruno, for example, you would reference Bruno's hair color this way:


This line of code would return whatever value was contained in the HairColor property of the Dog object Bruno. To set a property to some value, you use an equal sign (=). For example, to change the Dog object Bruno's Weight property, you'd use a line of code such as the following:

Bruno.Weight = 90

When you reference a property on the left side of an equal sign, you're setting the value. When you reference a property on the right side of the equal sign, you're getting (reading) the value. In the early days of BASIC, you actually used the word Let when setting values. This made the code easier to read for novices, but it was unnecessarily tedious. Nevertheless, using Let makes the statement clearer, so I'll show the same code statement as before with the word Let:

Let Bruno.Weight = 90

It's easier to see here that referencing the property on the left side of the equal sign indicates that you're setting the property to some value. The keyword Let is no longer a valid way to make variable assignments. If you enter a code statement that uses Let, you won't receive an error, but the code editor (also known as the gremlins) will automatically remove the word Let from the statement for you.

The following line of code places the value of the Weight property of the Dog object called Bruno into a temporary variable. This statement retrieves the value of the Weight property because the Weight property is referenced on the right side of the equal sign.

sngWeightVariable = Bruno.Weight

Variables are discussed in detail in Hour 11, "Using Constants, Data Types, Variables, and Arrays". For now, think of a variable as a storage location. When the processor executes this statement, it retrieves the value in the Weight property of the Dog object Bruno and places it in the variable (storage location) titled sngWeightVariable. Assuming that Bruno's Weight is 90, as set in the previous example, the computer would process the code statement like this:

sngWeightVariable = 90

Just as in real life, some properties can be read but not changed. Suppose that you have a Sex property to designate the gender of a Dog object. It's impossible for you to change a dog from a male to a female or vice versa (at least I think it is). Because the Sex property can be retrieved but not changed, it's known as a read-only property. You'll often encounter properties that can be set in design view but become read-only when the program is running.

One example of a read-only property is the Height property of the combo box control. Although you can view the value of the Height property in the Properties window, you can't change the value—no matter how hard you try. If you attempt to change the Height property using Visual Basic .NET code, Visual Basic .NET simply changes the value back to the default—eerie.

Note - The best way to determine which properties of an object are read-only is to consult the online help for the object in question.

Working with an Object and Its Properties

Now that you know what properties are and how they can be viewed and changed, you're going to experiment with properties in a simple project. In Hour 1, you learned how to set the Height and Width properties of a form using the Properties window. Now, you're going to change the same properties using Visual Basic .NET code.

The project you're going to create consists of a form with some buttons on it. One button will enlarge the form when clicked, whereas the other will shrink the form. This is a very simple project, but it illustrates rather well how to change object properties in Visual Basic code.

  1. Start by creating a new Windows Application project (from the File menu, choose New, Project).
  2. Name the project Properties Example.
  3. Use the Properties window to change the name of the form to fclsDrinkMe. (Click the form to once select it and you'll be able to change its Name in the Properties window.)
  4. Next, change the Text property of the form to Grow and Shrink.

When the project first runs, the default form will have a Height and Width as specified in the Properties window. You're going to add buttons to the form that a user can click to enlarge or shrink the form at runtime.

Add a new button to the form by double-clicking the Button tool in the toolbox. Set the new button's properties as follows:

PropertySet To
TextEat Me

Now for the Shrink button. Again, double-click the Button tool in the toolbox to create a new button on the form. Set this new button's properties as follows:

PropertySet To
TextDrink Me

Your form should now look like the one shown in Figure 3.2.

Image 3

Figure 3.2

Each button is an object, as is the form the buttons sit on.

To complete the project, you need to add the small amount of Visual Basic .NET code necessary to modify the form's Height and Width properties when the user clicks a button. Access the code for the Enlarge button now by double-clicking the Eat Me button. Type the following statement exactly as you see it here. Do not press the Enter key or add a space after you've entered this text.


When you typed the period, or dot, as it's called, a small drop-down list like the one shown in Figure 3.3 appeared. Visual Basic .NET is smart enough to realize that Me represents the current form (more on this in a moment), and to aid you in writing code for the object, it gives you a drop-down list containing all the properties and methods of the form. This feature is called IntelliSense, and it is relatively new to Visual Basic. When an IntelliSense drop-down box appears, you can use the up and down arrow keys to navigate the list, and press Tab to select the highlighted list item. This prevents you from misspelling a member name thereby reducing compile errors. Now that Visual Basic .NET is fully object-oriented, you'll come to rely on IntelliSense drop-down lists in a big way; I think I'd rather dig ditches than program without them.

Image 4

Figure 3.3

IntelliSense drop-down lists (also called auto-completion drop-down lists) make coding dramatically easier.

Use the Backspace key to completely erase the code you just entered and enter the following code in its place (press Enter at the end of each line):

Me.Width = Me.Width + 20
Me.Height = Me.Height + 20

You're probably wondering what you have to do with the width and height of the form. Actually the word Me doesn't refer to a person, it refers to the object to which the code belongs (in this case, the form). Me is a reserved word; it's a word that you can't use to name objects or variables because Visual Basic has a specific meaning for it. When writing code within a form module, as you're doing here, you should always use the reserved word Me rather than using the name of the form. Me is much shorter than using the full name of the current form, and it makes the code more portable (you can copy and paste the code into another form module and not have to change the form name to make the code work). Also, should you change the name of the form at any time in the future, you won't have to change references to the old name.

Note - Me works only in object-based modules such as form modules; you can't use Me in a standard module, which you'll learn about in Hour 10, "Creating and Calling Code Procedures."

The code you've entered does nothing more than set the Width and Height properties of the form to whatever the current value of the Width and Height properties happens to be, plus 20 pixels.

Redisplay the form designer by selecting the tab named Form1.vb [Design]. Then double-click the Shrink (Drink Me) button to access its Click event and add the following code:

Me.Width = Me.Width - 20
Me.Height = Me.Height - 20

This code is very similar to the code in the Enlarge_Click event, except that it reduces the Width and Height properties of the form by 20 pixels. Your screen should now look like Figure 3.4.

Tip - As you create projects, it's a very good idea to save frequently. Save your project now by clicking the Save All button on the toolbar.

The last step you need to perform is to specify the current form as the Startup object. Do this by right-clicking the Properties Example item in the Solution Explorer, choosing Properties, and then selecting fclsDrinkMe from the Startup object drop-down list. Click OK to close the Property Pages form.

Image 5

Figure 3.4

The code you've entered should look exactly like this.

Once again, display the form designer by clicking the tab Form1.vb [Design]. Your Properties Example project is now ready to be run! Press F5 to put the project in Run mode (see Figure 3.5).

Image 6

Figure 3.5

What you see is what you get—the form you created should look just as you designed it.

Click the Eat Me button a few times and notice how the form gets bigger. Next, click the Drink Me button to make the form smaller. When you've clicked enough to satisfy your curiosity (or until you get bored), end the running program and return to Design mode by clicking the Stop Debugging button on the toolbar.

Understanding Methods

In addition to properties, most objects have methods. Methods are actions the object can perform, in contrast to attributes that describe the object. To understand this distinction, think about the Pet object example. A Dog object has a certain set of actions that it can perform. These actions, called methods in Visual Basic, include barking, tail wagging, and chewing carpet (don't ask). Figure 3.6 illustrates the Dog object and its methods.

Image 7

Figure 3.6

Invoking a method causes the object to perform an action.

Triggering Methods

Think of methods as functions—which is exactly what they are. When you invoke a method, code is executed. You can pass data to a method, and methods can return values. However, a method is neither required to accept parameters (data passed by the calling code) nor to return a value; many methods simply perform an action in code. Invoking (triggering) a method is similar to referencing the value of a property: You first reference the object's name, and then a dot, and then the method name as shown next:


For example, to make the hypothetical Dog object Bruno bark using Visual Basic .NET code, you would use this line of code:


Note - Methods are generally used to perform an action using an object, such as saving or deleting a record in a database. Properties, on the other hand, are used to get and set attribute values of the object. One way to tell in code whether a statement is a property reference or method call is that the method call will have a set of parentheses after it, as in


Invoking methods is simple; the real skill lies in knowing what methods an object supports and when to use a particular method.

Understanding Method Dynamism

Properties and methods go hand in hand, and at times a particular method might become unavailable because of one or more property values. For example, if you were to set the NumberofLegs on the Dog object Bruno equal to zero, the Walk and Fetch methods would obviously be inapplicable. If you were to set the NumberofLegs property back to four, you could then trigger the Walk or Fetch methods again.

Building a Simple Object Example Project

The only way to really grasp what objects are and how they work is to use them. I've said this before, but I can't say it enough: Everything in Visual Basic .NET is an object. This has its good points and its bad points. One of the bad points is that in some instances, it now takes more code to accomplish a task than it did before—sometimes more characters, sometimes more statements. The functionality of Visual Basic .NET, on the other hand, is head and shoulders above Visual Basic 6. This has the effect of giving Visual Basic .NET a steeper learning curve than any previous version of Visual Basic.

Every project you've built so far uses objects, but you're now going to create a sample project that specifically illustrates using objects. If you're new to programming with objects, you'll probably find this a bit confusing. However, I'll walk you through step-by-step, explaining each section in detail.

The project you're going to create consists of a single form with one button on it. When the button is clicked, a line will be drawn on the form beginning at the upper-left corner of the form and extending to the lower-right corner.

Note - In Hour 18, "Working with Graphics", you'll learn all about the drawing functionality within Visual Basic.

Creating the Interface for the Drawing Project

Follow these steps to create the interface for your project:

  1. Start Visual Basic .NET.
  2. Create a new Windows Application project titled Object Example.
  3. Rename the default form fclsObjectExample (by using the Properties window), and change the form's Text property to Object Example.
  4. Make this form the Startup object by right-clicking Object Example in the Solution Explorer window, choosing Properties, and then selecting fclsObjectExample from the Startup object drop-down list. Click OK to close the dialog box.
  5. Add a new button to the form and set its properties as shown in the following table:

Writing the Object-Based Code

You're now going to add code to the Click event of the button. I'm going to explain each statement, and at the end of the steps, I'll show the complete code listing.

  1. Double-click the button to access its Click event.
  2. Enter the first line of code as follows (remember to press Enter at the end of each statement):
    Dim objGraphics As Graphics

    Here you've just created a variable that will hold an instance of an object. Objects don't materialize out of thin air; they have to be created. When a form is loaded into memory, it loads all its controls (that is, creates the control objects), but not all objects are created automatically like this. The process of creating an instance of an object is called instantiation. When you load a form, you instantiate the form object, which in turn instantiates its control objects. You could load a second instance of the form, which in turn would instantiate a new instance of the form and new instances of all controls. You would then have two forms in memory, and two of each used control.

    To instantiate an object in code, you create a variable that holds a reference to an instantiated object. You then manipulate the variable as an object. The Dim statement you wrote in step 2 creates a new variable called objGraphics, which holds a reference to an object of type Graphics. You learn more about variables in Hour 11.

  3. Enter the second line of code exactly as shown here:
    objgraphics = Me.CreateGraphics

    CreateGraphics is a method of the form (remember, the keyword Me is shorthand for referencing the current form). Under the hood, the CreateGraphics method is pretty complicated, and I discuss it in detail in Hour 18. For now, understand that the method CreateGraphics instantiates a new object that represents the client area of the current form. The client area is the gray area within the borders and title bar of a form. Anything drawn onto the objGraphics object will appear on the form. What you've done is set the variable objGraphics to point to an object that was returned by the CreateGraphics method. Notice how values returned by a property or method don't have to be traditional values such as numbers or text; they could also be objects.

  4. Enter the third line of code as shown next:

    This statement clears the background of the form using whatever color the user has selected as the Windows Control color, which Windows uses to paint forms.

    How does this happen? In step 3, you used the CreateGraphics method of the form to instantiate a new Graphics object in the variable objGraphics. With the code statement you just entered, you're calling the clear method of the objGraphics object. The Clear method is a method of all Graphics objects used to clear the graphic surface. The Clear method accepts a single parameter: the color you want used to clear the surface.

    The value you're passing to the parameter looks fairly convoluted. Remember that "dots" are a way of separating objects from their properties and methods (properties, methods, and events are often called object members). Knowing this, you can discern that System is an object (technically it's a namespace, as discussed in Appendix A, "The 10,000-Foot View," but for our purposes it behaves just like an object) because it appears before any of the dots. However, there are multiple dots. What this means is that Drawing is an object property of the System object; that is, it's a property that returns an object. So, the dot following Drawing is used to access a member of the Drawing object, which in turn is a property of the System object. We're not done yet, however, because there's yet another dot. Again, this indicates that SystemColors, which follows a dot, is an object of the Drawing method, which in turn is...well, you get the idea. As you can see, object references can and do go pretty deep, and you'll use many dots throughout your code. The key points to remember are:

    • Text that appears to the left of a dot is always an object (or namespace).
    • Text that appears to the right of a dot is a property reference or method call. If the text is followed by a set of parentheses, it's a method call. If not, it's a property.

    Methods can return objects, just as properties can. The only surefire ways to know whether the text between two dots is a property or method is to look at the icon of the member in the IntelliSense drop-down or to consult the documentation of the object.

    The final text in this statement is the word Control. Because Control isn't followed by a dot, you know that it's not an object; therefore, it must be a property or method. Because you expect this string of object references to return a color value to be used to clear the graphic object, you know that Control in this instance must be a property or a method that returns a value (because you need the return value to set the Clear() method). A quick check of the documentation would tell you that Control is indeed a property. The value of Control always equates to the color designated on the user's computer for the face of forms and buttons. By default, this is a light gray (often fondly referred to as battleship gray), but users can change this value on their computers. By using this property to specify a color rather than supplying the actual value for gray, you're assured that no matter the color scheme used on a computer, the code will clear the form to the proper system color. System colors are explained in Hour 18.

  5. Enter the following statement. (Note: Do not press Enter until you're done entering all the code shown here. The code appears on two lines only because of the size restriction of this page.)
    objgraphics.DrawLine(system.Drawing.Pens.Blue, 0, 0,
               Me.DisplayRectangle.Width, Me.DisplayRectangle.Height)

    This statement draws a blue line on the form. Within this statement is a single method call and three property references. Can you tell what's what? Immediately following objGraphics (and a dot) is DrawLine. Because no equal sign is present, you can deduce that this is a method call. As with the Clear method, the parentheses after DrawLine are used to enclose a value passed to the method. The DrawLine accepts the following parameters in the order in which they appear here:

    • A pen
    • X value of first coordinate
    • Y value of first coordinate
    • X value of second coordinate
    • Y value of second coordinate

    The DrawLine method draws a straight line between coordinate one and coordinate two, using the pen specified in the Pen parameter. I'm not going to go into detail on pens here (refer to Hour 18), but suffice it to say that a pen has characteristics such as width and color. Looking at the dots once more, notice that you're passing the Blue property of the Pens object. Blue is an object property that returns a predefined Pen object that has a width of 1 pixel and the color blue.

    You're passing 0 as the next two parameters. The coordinates used for drawing are defined such that 0,0 is always the upper-left corner of a surface. As you move to the right of the surface, X increases, and as you move down the surface, Y increases; you can use negative values to indicate coordinates that appear to the left or above the surface. The coordinate 0,0 causes the line to be drawn from the upper-left corner of the form's client area.

    The object property DisplayRectangle is referenced twice in this statement. DisplayRectangle is an object of the form that holds information about the client area of the form. Here, you're simply getting the Width and Height properties of the client area and passing them to the DrawLine method. The result is that the end of the line will be at the lower-right hand corner of the form's client area.

  6. Lastly, you have to clean up after yourself by entering the following code statement:

    Objects often make use of other objects and resources. The underlying mechanics of an object can be truly boggling and are almost impossible to discuss in an entry-level programming book. The net effect, however, is that you must explicitly destroy most objects when you're done with them. If you don't destroy an object, it might persist in memory and it might hold references to other objects or resources that exist in memory. This means you can create a memory leak within your application that slowly (or rather quickly) munches system memory and resources. This is one of the cardinal no-no's of Windows programming, yet the nature of using resources and the fact you're responsible for telling your objects to clean up after themselves makes this easy to do. If your application causes memory leaks, your users won't call for a plumber, but they might reach for a monkey wrench....

    Objects that must explicitly be told to clean up after themselves usually provide a Dispose method. When you're done with such an object, call Dispose on the object to make sure it frees any resources it might be holding.

    For your convenience, here are all the lines of code:

    Dim objGraphics As Graphics
    objgraphics = Me.CreateGraphics
    objgraphics.DrawLine(system.Drawing.Pens.Blue, 0, 0, _
               Me.DisplayRectangle.Width, Me.DisplayRectangle.Height)

    The statement calling DrawLine is shown here as two lines of code. At the end of the first line is an underscore (_). This character is a special character called a line continuation character, and it tells the Visual Basic compiler that the statement immediately following the character is a continuation of the current statement. You can, and should, use this character to break up long statements in your code.

Testing Your Object Example Project

Now the easy part. Run the project by pressing F5 or by clicking the Start button on the toolbar. Your form looks pretty much like it did at design time. Clicking the button causes a line to be drawn from the upper-left corner of the form's client area to the lower-right corner (see Figure 3.7).

Note - If you receive any errors when you attempt to run the project, go back and make sure that the code you entered exactly matches the code I've provided.

Image 8

Figure 3.7

Simple lines and complex drawings are accomplished using objects.

Resize the form, larger or smaller, and click the button again. Notice that the form is cleared and a new line is drawn. If you were to omit the statement that invokes the Clear method (and you're welcome to stop your project and do so), the new line would be drawn, but any and all lines already drawn would remain.

Note - If you use Alt+Tab to switch to another application after drawing one or more lines, the lines will be gone when you come back to your form. In fact, this will occur anytime you overlay the graphics with another form. In Hour 18, you'll learn why this is so and how to work around this behavior.

Stop the project now by clicking Stop Debugging on the Visual Basic .NET toolbar and then click Save All to save your project. What I hope you've gained from building this example is not necessarily that you can now draw a line (which is cool), but rather an understanding of how objects are used in programming. As with learning almost anything, repetition aids in understanding. That said, you'll be working with objects a lot throughout this book.

Understanding Collections

A collection is just what its name implies: a collection of objects. Collections make it easy to work with large numbers of similar objects by enabling you to create code that performs iterative processing on items within the collection. Iterative processing is an operation that uses a loop to perform actions on multiple objects, rather than writing the operative code for each object. In addition to containing an indexed set of objects, collections also have properties and might have methods. Figure 3.8 illustrates the structure of a collection.

Image 9

Figure 3.8

Collections contain sets of like objects, and they have their own properties and methods.

Continuing with the Dog/Pet object metaphor, think about what an Animals collection might look like. The Animals collection might contain one or more Pet objects, or it might be empty (contain no objects). All collections have a Count property that returns the total count of objects contained within the collection. Collections might also have methods, such as a Delete method used to remove objects from the collection and an Add method used to add a new object to the collection.

To better understand collections, you're going to create a small Visual Basic .NET project that cycles through the Controls collection of a form and tells you the value of the Name property of every control on the form. To create your sample project, follow these steps:

  1. Start Visual Basic now (if it's not already loaded) and create a new Windows Application project titled Collections Example.
  2. Change the name of the form to fclsCollectionsExample using the Solution Explorer and set the form's Text property to Collections Example.
  3. Make this form the Startup object by right-clicking Collections Example in the Solution Explorer window, choosing Properties, and then selecting fclsCollectionsExample from the Startup object drop-down list. Click OK to close the dialog box.
  4. Add a new button to the form by double-clicking the Button tool in the toolbox. Set the button's properties as follows:
    TextShow Control Names
  5. Next, add some text box and label controls to the form. As you add the controls to the form, be sure to give each control a unique name. Feel free to use any name you like, but you can't use spaces in a control name. You might want to drag the controls to different locations on the form so that they don't overlap.
  6. When you're finished adding controls to your form, double-click the Show Control Names button to add code to its Click event. Enter the following code:
    Dim intIndex As Integer
    For intIndex = 0 To Me.Controls.Count - 1
      MessageBox.Show("Control #" & intIndex & " has of the name " & _
    Next intIndex

    Note - Every form has a Controls collection, which might or might not contain any controls. Even if no controls are on the form, the form still has a Controls collection.

  7. The first statement should look familiar to you by now. As with the Object Example you created earlier, this statement creates a variable to hold a value. Rather than create a variable that can hold an object, as you did in the earlier example, this statement creates a variable that can hold only a number.
  8. The next statement (the one that begins with For) accomplishes a few tasks. First, it initializes the variable intIndex to 0, and then it starts a loop (loops are discussed in Hour 14, "Looping for Efficiency"), incrementing intIndex by one until intIndex equals the number of controls on the form, less one. The reason you subtract one from the Count property is that collections are zero-based—the first item is always item zero. Thus, the first item is in location zero, the second item is in location one, and so forth. If you tried to reference an item of a collection in the location of the value of the Count property, an error would occur because you would be referencing an index that's one higher than the actual locations within the collection.
  9. The MessageBox.Show() method (mentioned in Hour 2, "Navigating Visual Basic .NET," and discussed in detail in Hour 17, "Interacting with Users") is a class of the .NET Framework that's used to display simple dialog boxes with text. The text that you're providing, which the Show method will display, is a concatenation of multiple strings of text. (Concatenation is the process of adding strings together; it's discussed in Hour 12, "Performing Arithmetic, String Manipulation, and Date/Time Adjustments".)

Run the project by pressing F5 or by clicking Start on the toolbar. Ignore the additional controls that you placed on the form and click the Show Control Names button. Your program will then display a message box similar to the one shown in Figure 3.9 for each control on your form (because of the loop). When the program is finished displaying the names of the controls, choose Stop Debugging from the Debug toolbar to stop the program, and then save the project.

Image 10

Figure 3.9

The Controls collection enables you to get to each and every control on a form.

Because everything in Visual Basic .NET is an object, you can expect to use numerous collections as you create your programs. Collections are powerful, and the quicker you become comfortable using them, the more productive you'll become.

Using the Object Browser

Visual Basic .NET includes a useful tool that enables you to easily view members (properties, methods, and events) of all the objects in a project: the Object Browser (see Figure 3.10). This is extremely useful when dealing with objects that aren't well documented because it enables you to see all the members an object supports. To view the Object Browser, choose Object Browser from the View menu.

The Browse drop-down list in the upper-left corner of the Object Browser is used to determine the browsing scope. You can choose Active Project to view only the objects referenced in the active project, or you can choose Selected Components (the default) to view a set of selected objects. The Object Browser shows a preselected set of objects for Selected Components, but you can customize the object set by clicking the Customize button next to the Browse drop-down list. I don't recommend changing the custom object setting until you have some experience using Visual Basic objects as well as experience using the Object Browser.

Image 11

Figure 3.10

The Object Browser enables you to view all properties and methods of an object.

The top-level nodes in the Objects tree are libraries. Libraries are usually DLL or EXE files on your computer that contain one or more objects. To view the objects within a library, simply expand the library node. As you select objects within a library, the list to the right of the Objects tree will show information regarding the members of the selected object (refer to Figure 3.10). For even more detailed information, click a member in the list on the right, and the Object Browser will show information about the member in the gray area below the two lists.


In this hour, you learned all about objects. You learned how objects have properties, which are attributes that describe the object. Some properties can be set at runtime using the Properties window, and most can also be set at runtime in Visual Basic .NET code. You learned that referencing a property on the left side of the equal sign has the effect of changing a property, whereas referencing a property on the right side of the equal sign retrieves a property's value.

In addition to properties, you learned that objects have executable functions, called methods. Like properties, methods are referenced by using a dot at the end of an object reference. An object might contain many methods and properties, and some properties can even be objects themselves. You learned how to "follow the dots" to interpret a lengthy object reference.

Objects are often used as a group, called a collection. You learned that a collection often contains properties and methods, and that collections let you easily iterate through a set of like objects. Finally, you learned that the Object Browser can be used to explore all the members of an object in a project.

The knowledge you've gained in this hour is fundamental to understanding programming with Visual Basic because objects and collections are the basis on which applications are built. After you have a strong grasp of objects and collections—and you will have by the time you've completed all the hours in this book—you'll be well on your way to fully understanding the complexities of creating robust applications using Visual Basic .NET.


  1. Is there an easy way to get help about an object's member?
  2. Absolutely. Visual Basic .NET's context-sensitive Help extends to code as well as to visual objects. To get help on a member, write a code statement that includes the member (it doesn't have to be a complete statement), position the cursor within the member text, and press F1. For instance, to get help on the Count property of the Controls collection, you could type Me.Controls.Count, position the cursor within the word Count, and press F1.
  3. Are there any other types of object members besides properties and methods?
  4. Yes. An event is actually a member of an object, although it's not always thought of that way. Not all objects support events, however, but most objects do support properties and methods.


The Workshop is designed to help you anticipate possible questions, review what you've learned, and get you thinking about how to put your knowledge into practice. The answers to the quiz are in Appendix B, "Answers to the Quizzes."


  1. True or False: Visual Basic .NET is a true object-oriented language.
  2. An attribute that defines the state of an object is called a ____________.
  3. To change the value of a property, the property must be referenced on which side of an equal sign?
  4. What is the term for when a new object is created from a template?
  5. An external function of an object (one that is available to code using an object) is called a ____________.
  6. True or False: A property of an object can be another object.
  7. A group of like objects is called a ____________.
  8. What tool is used to explore the members of an object?


  1. Create a new project and add text boxes and a button to the form. Write code that, when clicked, places the text in the first text box into the second text box. Hint: Use the Text property of the text box controls.
  2. Modify the collections example in this hour to print the height of all controls, rather than the name.


This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


About the Author

Sams Publishing
United States United States
No Biography provided
Group type: Organisation

1 members

Comments and Discussions

GeneralMore interesting to understand Pin
Member 117024429-Jun-04 20:51
MemberMember 117024429-Jun-04 20:51 
Tell me other latest books that will lead me towards gaining confident....
Questionwrong section? Pin
.dan.g.18-Feb-04 18:14
professional.dan.g.18-Feb-04 18:14 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.