Beginning
Overview
IDE
Projects
Forms
Controls
Intrinsic Ctrls
ActiveX Ctrls
Code
Commands
Cmd Reference
File Handling
Printing
Distribution

Intermediate
Menus
Dialogs
Mouse
Drag and Drop
Graphics
Error Handling
Databases
Database Controls
SQL

Advanced
API
Objects
Internet File Transfers
UNIX/CGI/Perl
Perl Commands
JavaScript
Web Page Forms

GBIC >> VB >> Tutorials >> Objects
Objects
Since VB4, Microsoft has been promoting the "object-oriented" aspects of Visual Basic. It seems like everything you read is object-this and object-that! So what is the real story about objects? Who needs them, and why? How do you use them and when are they overkill? Can you use them without having to be an expert in all aspects of objects? If you're like me, a solo programmer whose contact with the VB world is limited to email and magazines, do the answers apply to you? I'm interested in writing the tutorial as much to find out the answers myself, as you are to get the answers!


Introduction to Objects

Let's get down the bottom line quickly. Objects are a combination of code and data which you can treat as a single item. You have already worked with objects - the controls and forms in a VB project. So the purpose of this tutorial is not so much to explain what they are, but rather to go into the details of how they work and how you can use them in your own programs. There is a lot more to objects than just drawing a control on your form and that's what we want to cover here. We'll especially get into how you create and handle objects in code, which is much different than simply drawing controls onto a form!

In case you have any question about the value of objects, let me state without reservation, that objects (in the form of controls) are the single biggest reason why VB has been so successful. In more recent versions of VB, Microsoft has expanded the object features of VB, making it even more powerful than ever.

The availability of powerful tools does not automatically guarantee success. From my viewpoint, the jury is still out on how useful these newer features are going to be for the average programmer! I have no doubts about the power of the newer tools, but just like 70% of Excel/Word capabilities are never applied by users, so too are many of VB's object-oriented features going unused by most programmers.

VB is known for its ability to allow a programmer to quickly, and easily, create a Windows program. In part, this is possible because objects provide code which you don't have to write! I cannot say this with enough force! Objects are written by programmers to provide certain capabilities which you can access by executing the code with the objects. In a way, this makes objects just another way of creating a code library - similar in function to the use of API that you learned in the last tutorial!

However, don't mistake my simple comparison to imply that objects are as easy to use as are the API. They're not! You'll spend a lot more time studying how to work with objects. Mastering how to use API is a one-day session, with additional time spent on figuring out which API to use. Learning to master the use of objects, however, is going to be one of the major study tasks that you undertake in VB.

Some parts of objects usage are actually pretty simple. Some, however, are very complex. In this tutorial we'll work our way up from the simple to the difficult.

You'll have to make a personal assessment as to the extent to which you implement the range of object-oriented capabilities that VB offers. You may find that your applications work fine with just the use of the basic controls that come with VB or by using the Windows API when VB falls short. You may also find that you cannot get the functionality from you want from your application or that you cannot reach the level of efficiency at creating applications without depending heavily on objects.

In the end, I suggest that the criteria for using objects is whether they help you get the job done with less effort than it would take to do the job without them! My personal experience is that limited application of object programming is adequate to do just about anything I need to do. I'll admit that I'm having trouble relating my own experience with the object-intensive media blitz that you see in the VB magazines today.

There's an old saying that to someone with a hammer, everything looks like a nail! The moral to the story is that you should develop skills with new tools in order to evaluate which one applies to certain jobs. Let's begin that development right now!

What are Objects?
I gave a definition earlier - objects are a combination of code and data. But let's expand on the idea. Equally key is the idea that the code/data combination can be handled as a single item. If you copy the object, both the code and data go with it. If you save the object, both the code and data get saved.

Examples are an easy way for you to understand what VB treats as object:

  • Command Button - In fact, any of the VB controls are objects.
  • Form - Just like controls, forms are objects.
  • Database - Even though it doesn't have a windows, like a control, a database is still an object.

These are all examples of objects to which you should have already been exposed as part of your VB training.

Properties, Methods, and Events
Later, we'll get more into creating your own objects. But for now, let's look at how to use them. All objects share a common way of accessing the data and code that we've said make up an object.

The data inside an object is known as the properties of the object. In familiar terms, it corresponds to the values of variables which are stored inside the object. For example, all objects have names. The name is one of the properties of the object and the way that you access a property in code is as follows:

tempString = ObjectName.Name
In this simple example, a variable called "tempString" is filled with the Name of an object. All properties of objects work exactly the same way, using what is called the "dot" notation. Here are some more examples:
h = Form1.height
w = listbox1.fontname
r = textbox.backcolor
g = timer1.interval
In each of these examples, a variable on the left is assigned the value of the property on the right. The format for identifying the property name is also done the same in every case - "objectname.propertyname".

Typically, whoever creates the object "exposes" properties which you can access. In the VB IDE environment you can click on a control and the properties box (press F4) will display all of the property names along with possible values for those properties. Object properties are just like variable in that they can have a type. They can be integer, string, dates, or any other VB data type. So remember when assigning property values to variables that the VB rules for type conversion must be taken into consideration.

When in the IDE code windows, VB also provides a big help in remembering the properties of an object. Once you've type in the object name and the ".", VB will display a dropdown listbox which give all of the available properties.

Two other nuances about properties will be of interest. First of all, not all properties of an object are "exposed" for use in your VB program. When we get around to creating our own objects in code, you'll find that you can choose whether to expose a property for use in code, or whether to keep it hidden within the object (so as not to allow its value to get changed).

Also, ... (author mind block - as soon as I remember the other nuance, I'll put it here ).

COM & Exposed Objects
One of the key features about objects is that they can be made available outside of an application for use by other programmers. Making an object available for use is known as "exposing" the object. Many of the major applications such as Word or Excel expose objects for your use. Microsoft has established a standard known as COM (Common Object Model) which guides programmers through the techniques of exposing objects from within their applications.

Exposed objects cannot, however, be distributed with your application. If you plan to create an application which uses exposed objects from a second application, then your user must have that second application installed on his PC. This is not a trivial problem. Unless you have some control over the user's environment you'll find it best to distribute stand-alone applications - ones which do not assume that any particular software is resident on your user's PCs.

All controls, whether in the form of ActiveX Controls (.OCX files) or in the form of exposed objects, must be registered with Windows (as part of the Registry) before your VB program can use the object. In the VB IDE you can call up the Components Dialog Box which will list all of the objects (ActiveX files or exposed objects) thtat are available for your use. If you select one of the objects for use, the object will appear on your VB IDE toolbox and can then be used just like any of the intrinsic controls that you have already used.

There is a utility called regsvr32.exe that comes with Windows which you will find very useful. Regsvr32 allows you to manually register an OCX in the registry. The need to do this manually can arise for a variety of reasons, but mostly because an installation program failed to automatically make the registration. The code to register an OCX file is:

regsvr32 filename.ocx
You can do this from a DOS command line or through the Start/Run menu option.

Classes
We're just about to get into the How of creating objects, but one more topic needs discussion first. Before an object can be created, an object template must first be created. Once that template is created a copy can be created. It's the copy with which you will work in your VB programs.

In VB terminology, the template is called a class and the copies of the template are called instances. In the registration process that we just discussed, it is the template, or class, of an object that gets registered with Windows.

Object Browser
VB provides a tool with which you can browse all registered objects, including the properties and methods which they expose. The Object Browser window can be displayed by pressing F2 within the VB IDE. One advantage of the Object Browser over the properites window is that the browser can show both properties and methods of the registered classes. Additionally, the browser shows all registered objects, including the objects exposed by applications that you have installed on your PC. It's the poor man's documentation of all usable classes on your PC!

Creating Objects - References, Class Modules, & Collections
You can create objects at both design time and run time. Controls, forms, and class modules are examples of objects which you can create at design time (within the VB IDE). You can also create controls and form objects at run time, as well as creating variable objects and collections at run time. We'll cover these topics next in the tutorial.

  • References
    It is possible use the DIM function to create a variable whose type is that of any registered class. To do so, use this code:
    Dim X as ListBox
    
    Variables which have been defined as an object type are useful because they can be made to refer to an existing object. For example, this code, when used with the line of code just given, associates X with the ListBox1 control.
    Set X = ListBox1
    
    Notice the use of the Set statement? To establish a variable reference to an object, you cannot simply use the equal sign. You must use the SET statement.

    There are several reasons why you should be interested in creating a second reference to a control.

    First of all, once the variable is set to reference the control, all of the control's properties and methods and be accessed as follows:

    X.name
    is the same as
    ListBox1.name
    
    If nothing else, using variables rather than the full name of the control can save you some typing as you write your code.

    However there are other, more pressing reasons why the use of object variables in code is valuable. Later, we'll get into the idea of Collections, which represent a way to group objects so that you can address them one by one in code. It's similar to the concept of an array of objects, but the code for accessing a collection is different. I bring it up now because the following code for walking through a collection of objects demonstrates why the use of object variables is so valuable in VB:

    Dim X as Control
    For Each X in Form1.Controls
       If X.Top > 500 then
           MSGBox "It is below the line"
       End If
    Next X
    
    What this code does is to walk through all controls on Form1 (the Controls collection) and see if the top of the control is below the position 500. The magic to this code is that the object variable X was successively assigned a reference to every control on the form, and we could access the Top property of each control simply by using the variable X! Otherwise we would have had to put code which specifically named every single control and evaluated its Top property. The use of an object variable made it possible to significantly reduce the amount of coding that I had to do!

    There is a variation on the use of the Set statement which you should learn, and that is the Keyword "New". Elsewhere in these tutorials we

  • Collections
    VB also supports an object know as a collection. A collection object is exactly what the name implies - a group of objects whose properties can be addressed through code. And as the example above showed, it is not necessary to code the individual names of each member of the collection.

    VB provides the fairly simple means of working with collections. A collection has only one property, which is "Count", the number of objects in the collection. When an object is added to a collection it is given an index, with the first object index starting at zero. To address an object in a collection you can use either it's name, or its index as follows:

    • Specify the name of the object:
      Controls("List1")
      Controls!List1
      
    • Specify the index number of the object
      Controls(3)
      

    A collection also has only three methods:

    • Add
      Allows you to add members to a collection.Optional. One thing to note is that when you add a member to a collection you can give it a unique string (a key) that can be used, instead of a positional index, to access that member in the future.
    • Remove
      Allows you to remove members from a collection, either by specifying the index number of the object or its key.
    • Item
      Returns a specific member of a collection, either by numer or by key.

    Finally the loop construct I gave above is worth repeating because you can now see how it applies to collections.

    Dim X as Control
    For Each X in Form1.Controls
       If X.Top > 500 then
           MSGBox "It is below the line"
       End If
    Next X
    

    The "For Each" structure provde the ability to walk through every member of a collection ("Controls" in this example) and then operate on each member as your code/application requires.

    As you'll see collections have become an integral and important part of the VB coding environment. The example I just gave shows that using a collection (VB built-in collections managed by VB or collections which you can create yourself) can save you a lot of time and effort.

    The old Texas saying "If you don't own an oil well, then get one!" very much applies to collections. Not only can you save coding time and effort as I showed in the example, but you'll find that even the controls which comes with VB contain collections of their own. Whether you want to or not, collections are one area where you'll be forced into learning about them simply because they are becoming an integral part of the daily controls that you use.

  • Class Modules
    What we've discussed so far was perhaps the easier part of the tutorial. The real power that Microsoft has added with VB5 and VB6 has to do with the ability to create your own objects, including objects which you can expose to other applications and which you can compile separately and re-use in other applications.