Saturday, September 27, 2008

Techniques for Adding and Deleting Controls Dynamically

Occasionally you will create forms for which you do not always have a fixed number of controls. You may need to add controls at runtime or remove some of the controls that you have created. Visual Basic lets you create and destroy controls dynamically at runtime based on the needs of your application.

With VB6, you have at your disposal two major techniques for dynamic control creation:

*
Control arrays
*
Direct manipulation of the Controls Collection through the Add and Remove methods.

We discuss these techniques in the following two sections.


Adding and Deleting Controls Dynamically Using Control Arrays:
You must follow several rules to be able to create and remove controls with control arrays.

First you must have a control of the type that you will be adding placed on the desired form at runtime. If you will be adding TextBox controls to a form, for example, you must have at least one text box drawn on that form at design time. That control can be invisible, and there are no restrictions for the size or placement of that control, but it must be on the form at design time. This control will be the template for text boxes that you will add at runtime.

The second requirement for using dynamic control arrays is that the template object that you draw at design time must be part of a control array. Usually it is the only control of its type with its Index property set to a value of 0. Continuing with the text box example, you can have a form with only one text box as a template, and that text box must have its Index property set to some integer value (typically 0 or 1). If your application required it, you might have additional text boxes with Index values of 1, 2, 3, and so on.

As long as you have a control array with at least one object in it, you can create additional instances of that object dynamically at runtime.

After you have built a form with a control that has its Index property set, you can add additional controls to the control array at runtime. Assume, for example, that you have an application with one form, Form1, and one text box, Text1. Text1 has an Index value of 0. At runtime, you can create additional instances of Text1 on your form with code such as:

Load Text1 (index)

Method2:
Adding and Deleting Controls Dynamically Using the Controls Collection

The Add and Remove methods of the Controls Collection are new to VB6. You can use these methods to add and delete controls from a form instead of using the control array technique described in the previous section.

Following is an overview of the general steps that you need to take in order to dynamically add and remove controls with the Controls Collection (more detailed discussion is given in the following sections):

1.

Find out the control's ProgID, a unique string used by the Windows operating system (and stored in the Windows registry) for identifying the control's type.
2.

If the control is an intrinsic VB control, declare an object variable of the appropriate control type using WithEvents and program the resulting object's event procedures. If the control is an intrinsic VB control, then ignore steps 3, 6, and 7 that only apply to non-intrinsic controls.
3.

If the control is an ActiveX control (i.e., not an intrinsic VB control) then you must declare the type of its object variable as VBObjectExtender and place code in its ObjectEvent procedure to trap for the various events that you're interested in.
4.

Use the Add method of the Controls Collection to initialize the control with the ProgID that you determined in step 1, and set the result of the method to the object variable you declared in step 2 or 3. Set the control's Visible property to True and set any other properties that need to be changed. If the control is an ActiveX control, you'll need to refer to its members through the Object property of the control object variable.
5.

Use the Remove method of the Controls Collection to remove the control from the Controls Collection when your program is finished using the control.
6.

If an ActiveX control is in the Toolbox but is not otherwise referenced in your project with a design time instance on the surface of a form, then you must make sure that your project's properties are set appropriately to allow information about unused ActiveX controls to remain in the project.
7.

If an ActiveX control requires a license, then you must detect the control's license ID in your design time test environment and use that license ID to initialize the control in the compiled application that you distribute to end users. In order to do this legally, you must be licensed to use and distribute this control.

Using the StatusBar Contro

The StatusBar control is another ActiveX Control available through the Windows Common Controls components. With the StatusBar, you can easily display information about the date, time, and other details about the application and the environment to the user.
A StatusBar is made up of Panel objects, each of which displays different types of information. All the Panel objects are contained in the Panels Collection of the StatusBar. The appearance and purpose of each Panel is determined by the Style property of that Panel. The following styles are available:

*

sbrText (0) The Panel will display text information. The information displayed is in the Text property of the Panel.
*

sbrCaps (1) The Panel will contain the string "Caps". It will be highlighted if Caps Lock is turned on or disabled if Caps Lock is turned off.
*

sbrNum (2) The Panel will contain the string "Num". It will be highlighted if Num Lock is turned on or disabled if Num Lock is turned off.
*

sbrIns (3) The Panel will contain the string "Ins". It will be highlighted if Insert mode is turned on or disabled if Insert mode is turned off.
*

sbrScrl (4) The Panel will contain the string "Scrl". It will be highlighted if Scroll Lock is turned on or disabled if Scroll Lock is turned off.
*

sbrTime (5) The Panel will display the current time in the system format.
*

sbrDate (6) The Panel will display the current date in the system format.
*

sbrKana (7) The Panel will contain the string "Kana". It will be highlighted if Kana (a special character set only available in the Japanese PC market) is enabled or disabled if Kana is disabled.

Figure 4.12 shows an example of a status bar displaying all the different styles.

Different styles of the Panel object.
FIGURE 4.12 Different styles of the Panel object.

As with the other controls discussed in this chapter, the properties of the StatusBar and the Button objects can be set either through the Property Pages dialog box at design time or at runtime. The properties of the StatusBar control can be set on the General tab, as shown in Figure 4.13.

The Style and SimpleText properties of the toolbar determine the appearance of the control at runtime. The Style property can have one of two values: Simple or Normal. When the Style property is Simple, only one panel of the StatusBar is visible, and the text in the SimpleText property is displayed. When the Style property is Normal, the StatusBar appears with multiple panels.

General properties of the StatusBar.
FIGURE 4.13 General properties of the StatusBar.

Further properties of the Panel objects give more control over the appearance of a StatusBar control. These properties can be set on the Panels tab of the Property Pages dialog box, as shown in Figure 4.14, or at runtime.

Custom Properties of the Panel object.
FIGURE 4.14 Custom Properties of the Panel object.

The use of ToolTips is available to you with the StatusBar control. Behavior of ToolTips for the StatusBar is similar to the behavior of ToolTips for the ToolBar control (discussed earlier in "Using the ToolBar Control").

An individual ToolTipText property is available for each panel of the StatusBar control. When the ShowTips property of the StatusBar is set to True and the user rests the mouse pointer over a panel in the StatusBar, the ToolTipText is displayed at the mouse pointer.

Several other Panel properties affect the appearance of each panel. The Alignment property determines whether text displayed in a panel is left-justified, right-justified, or centered. The MinWidth property specifies the minimum width of a panel. The ScaleMode of the container on which the StatusBar is located determines the units for the MinWidth. Each panel also has a Width property that determines the starting width of the object.

The AutoSize property of a panel can also have an impact on its width. This property can have the following values:

*

sbrNoAutoSize (0) The panel size will not be changed automatically.
*

sbrSpring (1) If the size of the StatusBar increases as the size of the container grows, the width of the Panel will also increase. As a StatusBar grows smaller, the size of the Panel will not go below the MinWidth value.
*

sbrCntents (2) The Panel will be resized to fit its contents but will never fall below the MinWidth.

Another property that affects a panel's appearance is the Picture. Unlike the other controls discussed in this chapter, the StatusBar does not get images from an ImageList .

If you wish to include images—either bitmaps or icons—in a panel, you can add them through the Property Pages dialog box by specifying the file directly. You can also add them at runtime with the LoadPicture function, which takes the image file path as its argument, or by setting the Picture property to one of the ListImages in an ImageList control or to the appropriate bitmap property of some other control.

Using the ToolBar Control in VB6

In earlier 16-bit releases of Visual Basic, it was difficult to implement a toolbar for your users. You had to place a PictureBox control on a form and then add CommandButton controls to the PictureBox to simulate the toolbar. Starting with the 32-bit version of Visual Basic 4.0 and continuing with all subsequent versions of VB, you have the ToolBar ActiveX control that you can add to your forms to easily implement toolbar functionality for your users.

A toolbar is becoming a standard feature of Windows applications. Toolbars provide functionality to a user through an easily accessible, graphical interface. For common functions the user does not need to navigate through a menu or remember shortcut keys to use an application. Applications can expose their most common features through buttons on a toolbar.
Product Spotlight
Why are you still hand-coding?
Generate data entry and reporting .NET Web apps in minutes, straight from your database. Visually stunning, easy to customize and ready to deploy. Download Now!
Setting Custom Properties

The ToolBar control is available through the Windows Common Controls, along with the TreeView, ListView, and ImageList . After you have drawn a toolbar on a form, you will usually start by setting properties through the Property Pages dialog box for the control.

On the first tab of the Property Pages dialog box, as shown in Figure 4.9, one of the options you will set most often is the ImageList . Like the TreeView and the ListView controls, the toolbar gets images from an ImageList control. If you are building a toolbar that will have graphics on its buttons, you will first need to add an ImageList control to the form and then bind that ImageList to the toolbar through the Property Pages dialog box.

General tab of the Custom Properties of a toolbar.
FIGURE 4.9 General tab of the Custom Properties of a toolbar.

Several other properties are unique to the toolbar and can be set on the General tab. The ButtonHeight and ButtonWidth properties determine the size of buttons that appear on the toolbar. All buttons will have the same height and width. The number of buttons that can appear on a toolbar is determined by the size of the buttons and the width of the window. If you want the toolbar and buttons to wrap when the window is resized, you can set the Wrappable property of the toolbar to True.

Using the ListView Control

The ListView control displays lists of information to a user. As with the TreeView control, Windows Explorer provides an example of the ListView control. The left side of Windows Explorer contains a tree of all the directories on a drive. The right side contains a list of items within a directory. To get an idea of the ways in which a ListView control can be used, you just need to look at the way a list of files appears and behaves in Windows Explorer (see Figure 4.6).


FIGURE 4.6. Example of a ListView in Windows Explorer showing large icons

Objects can be displayed in one of four ways with the ListView. You can use either large or small icons to represent each item in the list, along with accompanying text information, where multiple items can appear on a single row. You can also display items in a list with one item per line. Finally you can how items as a columnar report in the ListView control with one item appearing on each line and sub-item information displaying in additional columns in the control, as shown in Figure 4.7.

Example of a ListView in Windows Explorer showing the report style.
FIGURE 4.7. Example of a ListView in Windows Explorer showing the report style.

As you learn about the ListView, you will see similarities to the TreeView control. The behavior and appearance of the two controls can be manipulated in many of the same ways. The major difference that you will notice is that objects in a ListView are not related to each other, as are objects in a TreeView.

Using the ImageList Control

The ImageList is a control that enables you to store graphic images in an application. Other controls can then use the ImageList as a central repository for the images that they will use. Both bitmaps (*.bmp files) and icons (*.ico files) can be stored in the ImageList control. At runtime the ImageList is invisible, just like a Timer or a CommonDialog control, so you can place it anywhere on a form without interfering with the user interface.

After an ImageList control has been added to a form, images can be added to the control at design time through the Custom Properties dialog box. The first tab of the dialog box, as shown in Figure 4.2, enables you to change general properties of the ImageList. On this tab, you can select the style and size of a graphic that will be included in the ImageList. Three of the resolutions, 16´16, 32´32, and 48´48, refer to the resolution of icon files. The Custom option lets you include bitmap images in the ImageList as well as icon images. You do not need to choose a resolution, height, and width for the ImageList. As soon as you add an image to the control, Visual Basic automatically determines the properties for you. After you have placed an image in the ImageList, you cannot change the resolution property. It is locked for as long as there is an image in the ImageList control.

The General tab of the Property Pages dialog box for the ImageList control.
FIGURE 4.2 The General tab of the Property Pages dialog box for the ImageList control.

The list of images contained in the ImageList control can be managed through the Images tab of the Property Pages dialog box, as shown in Figure 4.3. This tab enables you to add and remove images from the control as well as set additional information about each image. The Index of each image is assigned by Visual Basic. The Index starts at 1 for the first image and increments by 1 for each additional image.

The Images tab of the Property Pages dialog box for the ImageList control.
FIGURE 4.3 The Images tab of the Property Pages dialog box for the ImageList control.

You can use the Key property to refer to an image in the ImageList's collection of images. The Key property is a string value that you can use in place of the Index property to refer to an image in the list.

The easiest way to add images to the ImageList is to use the Images tab at design time. Just click on the Insert Picture button, and you can browse for the *.ico and *.bmp files that you want to add to the control.

After you have added images to the ImageList control, they are available for your application to use in other controls. You can load images into PictureBoxes and Image controls from the ImageList. The images can also be used by the other controls discussed later in this chapter, such as the ToolBar and ListView controls.

Although you can add all the images you may need in your application to the ImageList at design time, there are times when you will have to manipulate these images at runtime. This can be done through the ListImages Collection of the ImageList control. The ListImages Collection contains ListImage objects.

Introduction to Creating Data Input Forms and Dialog Boxes

You may include several standard 32-bit ActiveX controls on your form to enhance your Visual Basic application's user interface. These controls organize data and provide different ways of presenting information to the user, give you additional means of displaying information about the environment, and also provide the means for you—as a developer—to manipulate data and controls.

Here is a brief description of what the ActiveX controls discussed in this chapter do:

* The ImageList control gives you a means of loading graphics files, such as icons and bitmaps, into your application for use with other controls.

* You can use the ListView control to organize data in lists.

* The ToolBar control lets you quickly build toolbars in your application, giving users an alternative to the menu for performing actions.

* You can add the StatusBar to a form to present information about the environment to the user through text messages and progress bars.

We then discuss control arrays that allow your application to dynamically create and destroy controls as the application runs.

Next we examine the related concept of a form's Controls Collection that you can use to manipulate controls without referencing each by name.

Turning our attention to the manipulation of forms, we first discuss the different techniques for managing forms programmatically.

Finally we talk about how to manipulate the loaded forms in an application without referencing each form by name. As you might expect from the earlier description of the Controls Collection, we will use the Forms Collection.

JavaScript and HTML Tidy

For people who are not very good at writing their own HTML or who want to clean up the output from a WYSIWYG (what you see is what you get) web editor so that the HTML actually validates thhen using the HTML Tidy program originally written by Dave Raggett is probably the best solution. This program will fix most of the errors that might be in the HTML for you and even does a reasonable job of removing most of the garbage that Microsoft Word insists on writing into files when you ask it to output in HTML format.

The program even adjusts the formatting of the HTML file in order to make the source code easier to read and make it easier to spot the cause of those errors that it is unable to fix itself (mainly due to there usually being several possible things that you might have meant the code to do and the program is unable to decide which of them you intended).

This reformatting is a problem though if your page contains JavaScript particularly if that JavaScript is inside of a tag since the Tidy program will restructure the content of the textarea along with the rest of the web page which will convert any JavaScript that the textarea contains into complete garbage. It does this by inserting a whole lot of whitespace into various spots in the JavaScript where no whitespace is required and in some instances is not allowed.

The problem is that the program does not recognise that textarea content should not be reformatted when processing the page. His problem isn't just restricted to JavaScript as the same could happen with any text contained in a textarea that is required to be formatted a specific way.

There are two solutions to this problem, one alternative is to disable the reformatting completely when you run Tidy, the second is to go back and repair the page after Tidy has reformatted it.

To repair the page you first need to be aware of when you run HTML Tidy on a web page that contains a textarea. You then need to make sure that the update is not done in place where this applies so that you have access to the original version of the page in order to copy and paste the textarea content from the original into the reformatted copy of the page.

JavaScript and Unicode

ASCII only allows for 128 different characters and 32 of those are allocated to control characters leaving only 96 actual displayable characters that can be used. Manyof the world's languages use characters that do not fit within this small group. There are also a lot of special symbols used in specialized areas such as mathematics. To cater for this much larger range of characters in a standard way, the Unicode character set was developed. This matches the ASCII characters for the first 128 but provides a way of specifically identifying over 16 million different characters. All of the characters you are ever likely to need can be found somewhere in the Unicode charts. There are three different ways of specifying that a web page should display unicode characters. These are utf-8, utf-16, and utf-32. All three allow all characters to bbe used, the only difference is that the utf-8 will use a single byte for each character within the first 256 and will only use two or four bytes per character for those that need it while utf-16 will use at least two bytes per character and utf-32 will always use four bytes per character.

Unicode characters are specified in JavaScript by typing a backslash, a lowercase "u", and then the four digit hexadecimal number corresponding to the character's encoding in the utf-16 character set. This gives you the ability to reference the 65000+ most common characters that can be used in web pages from within your JavaScript code.

To make it easier for you to see what a given unicode value entered into your JavaScript represents, simply enter the four digit hexadecimal value that you intend to use into the following form and the actual character that it represents will be displayed in bold red text in the sentence below. (note that nothing will happen if you enter anything other than a valid four digit hexadecimal number).

\u
is the Unicode Character : " ".

One thing that you do need to watch for if you start using unicode characters in your web page is that there are a few javaScript functions that do not handle unicode. Each of these functions has been replaced in JavaScript by a new function that does support unicode but you will still see a lot of code around using the old non compliant functions. For example a lot of people still use escape() instead of encodeURI() or encodeURIComponent().

Not Quite Javascript

When most people think of Javascript they think of the scripting language that runs in their web browser. When most people think of the scripting language that runs in their web browser they think of Javascript.

In most instances when people relate these two items (web browser scripting language and Javascript) they haven't quite understood things properly. While modern browsers such as Firefox, Netscape, Mozilla, Opera, Safari, Konqueror etc do use Javascript as their built-in browser scripting language, the most popular browser (Internet Explorer) does not use Javascript at all. Instead Internet Explorer uses a similar scripting language called JScript.

Now you may not think this distinction is worth worrying about. You write your code to work on modern web browsers, add the alternate code where needed to handle Internet Explorer and just call it all Javascript. The thing is that JScript doesn't only run in the IE browser, it can also run on the web server under the .NET framework. Javascript only runs in the web browser (although it can run in places in the browser other than in the web page itself).

In fact there are a whole range of related languages of which Javascript and JScript are just two. What all of these languages have in connom is that they all are based on the ECMAscript standard which describes how the core language functions work.

Each of Javascript and JScript in fact have three component parts. Each has ECMAscript as one of those parts. The second part is the Document Object Model (DOM) and while Javascript implements the standard DOM quite well JScript doesn't implement it quite so well. To make up for this JScript implements a number of proprietary extensions to the DOM. The third part of each language is where the biggest differences occur as there is no standard Browser Object Model (BOM) and so browsers are free to define their own methods for web pages to access information about the browser. This difference is not as great as it used to be as most browsers now copy either the IE or Firefox BOM.

The other languages that are related to Javascript and JScript are also based on ECMAscript but as they do not directly run in a web page they don't have any veriant of the DOM and BOM although they do have equivalents that allow them to communicate with the environment that they run in the way that the DOM and BOM allow Javascript and JScript to communicate with the web page and the browser.

Microsoft actually provide a second language based on ECMAscript called Windows Scripting Host (WSH) which as the name suggests runs directly in Windows rather than in a web browser.

Adobe also have an ECMAscript based language called ActionScript which runs inside of Flash. ActionScript still uses the same core ECMAscript commands but substitutes a method for interacting with Flash components for the DOM and BOM of Javascript.

Yet another ECMAscript based language is Nombas ScriptEase.

All of these languages are based on exactly the same ECMAscript-262 standard which defines the core language. Once you have learned Javascript you should therefore find it relatively easy if you need to learn WSH, ActionScript, ScriptEase, or any other ECMAscript based language. I have even had people who couldn't find an ActionScript class who have taken my introductory Javascript class and found that it was just as applicable to what they were doing in Flash as for the web page use that I had intended when I designed the course.

One final thing to note is that ECMAscript has a number of reserved words that don't appear to be used in Javascript. If you look at the proposed Javascript 2.0 standard you will find many of those additional reserved words used there. Some of the other scripting languages based on ECMAscript are ahead of Javascript though and both JScript.NET running on the server and ActionScript have already implemented functionality that uses most of the "unused" reserved words.

Javascript and JScript

Netscape developed the original version of Javascript for the second version of their popular browser. Initially Netscape 2 was the only browser to support a scripting language and that language (which was originally going to be called LiveScript) was given the name Javascript in an attempt to cash in on some of the publicity that Sun's Java programming language was getting at that time. While Javascript and Java are superficially alike they are completely different languages and this naming decision has caused numerous problems for beginners with both languages who continually get them confused. Just remember that Javascript is not Java (and vice versa) and you will avoid a lot of confusion.

Microsoft was attempting to capture market share from Netscape at that time and so with Internet Explorer 3 they introduced two scripting languages. Once of these they based on visual basic and was given the name VBscript. The second was a Javascript lookalike which Microsoft called JScript. In order to try to outdo Netscape, JScript had a number of additional commands and features available that were not in Javascript and also had interfaces to Microsoft's activeX functionality as well.

Since Netscape 1, Internet Explorer 2, and other early browsers didn't understand either Javascript or JScript it became a common practice to place all of the content of the script inside of an HTML comment so as to hide the script from older browsers. New browsers even if they couldn't handle scripts were designed to recognise the script tags themselves and so hiding the script by placing it in a comment was not required for any browsers released after IE3. Unfortunately by the time that the extremely early browsers ceased to be used people had forgotten the reason for the HTML comment and so many people new to Javascript still include these now completely unnecessary tags. In fact including the HTML comment can cause problems since if you use XHTML instead of HTML including the code inside a comment like that will have the effect of making the script a comment rather than a script. Many modern Content Management Systems (CMS) will do the same.

Over time both Javascript and JScript were extended to introduce new commands to improve their ability to interact with web pages. Both languages added new features that worked differently than the corresponding feature (if any) in the other language. They were just similar enough that it was possible to use browser sensing to work out whether the browser was Netscape or IE and thus to run the appropriate code for that browser. As the balance shifted toward IE gaining an equal share of the browser market with Netscape this incompatibility needed a resolution.

Netscape's solution was to hand over control of Javascript to the European Computer Manufacturers Association (ECMA). The Association formalized the Javascript standards under the name ECMAscipt. At the same time the World Wide Web Consortium (W3C) commenced work on a standard Document Object Model (DOM) that would be used to allow Javascript and other scripting languages full access to manipulate all of the content of the page instead of the limited access that it had up until that time.

Before the DOM standard was complete both Netscape and Microsoft released their own versions. Netscape 4 came with its own document.layer DOM and Internet Explorer 4 came with its own document.all DOM. Both of these document object models were made obsolete when people ceased using either of those browsers as all browsers since then have implemented the standard DOM. ECMAscript and the introduction of the standard DOM in all of the version five and more recent browsers removed most of the incompatibilities between Javascript and JScript and while these two languages still have their differences it is now possible to write code that can run both as JScript in Internet Explorer and as Javascript in all of the other modern browsers. Support for specific features may vary between browsers but we can test for those differences by making use of a feature built into both languages from the start that allows us to test if the browser supports a specific feature. By testing the specific features that not all browsers support we will be able to determine what code is appropriate to run in the current browser.

The biggest difference now between Javascript and JScript are all of the additional commands that JScript supports that allow access to activeX and the local computer. These commands are intended for use on intranet sites where you know the configuration of all of the computers and that they are all running Internet Explorer. As these extensions in JScript should not be used on the internet I will not be covering any of them in this book. There are still a few areas remaining where Javascript and JScript differ in the means that they provide to perform a particular task. Where these occur, we will look at both the javascript and the JScript processes and how to combine them both into code that will work across all modern browsers. Except in these situations the two languages can therefore be considered to be equivalent to one another and so unless otherwise specified all of the references to Javascript can also be taken to include JScript

The Three Parts of JavaScript

Javascript and JScript each have the same three parts in their specifications.

The core component of the language (which is basically the same in both JavaScript and JScript) is based on the ECMAscript 262 standard. This standard defines how the core part of the language works. This includes the syntax to use to define your variables, how to perform calculations on those variables, how to set up loops and functions and how to define objects. What this standard doesn’t define is how the script should interface with the web page and the browser.

The second component part of the language is the Document Object Model (DOM). This standard has been developed by the W3C and defines how JavaScript should communicate with the web page in order to extract content from the page for processing, add content to the page, as well as how to access the stylesheet for the page in order to change the appearance of the page. There are four different “levels” in this set of standards. The DOM0 “standards” are those methods that the browsers implemented prior to the W3C starting on writing the standards and which the browsers still support today. The W3C has released three different sets of standards for interfacing with the web page each of which includes everything in the prior standard and which then adds further ways of interfacing with the page. These are known as DOM1, DOM2, and DOM3. The DOM3 standard is considered to be the final version with no further additions to it being required. Most browsers currently support most or all of the DOM2 standard and small parts of the DOM3 standard. Internet Explorer is somewhat behind the other browsers and still has some gaps in its support for DOM2 although JScript does also provide some alternatives that provide similar functionality.

The third and final component is the Browser Object Model which is how the scripts obtain information from the browser and pass information back to it. For this part of the language there is no one actually co ordinating standards and so the browser writers can define their own interface. Most browsers other than Internet Explorer have copied the Firefox way of interfacing to the browser which simplifies the task somewhat. Internet Explorer has two different ways of interfacing with the browser depending on whether the browser is being run in standards mode or quirks mode. Since this is determined by whether the page has a valid DOCTYPE statement as the first tag in the HTML file and this is under your control all of the discussion in this book will assume that you have set up your web page to run in standards mode in Internet Explorer and so we will disregard the quirks mode interface for Internet Explorer.

Javascript 101

Prerequisites

Perhaps you are just looking for information on where to get pre-built Javascripts to use on your site. Alternatively, you may want to learn how to write your own javascripts. In either case the two things that you most definitely need are a web editor and one (or more) browsers.

You need the web editor to edit your web pages to add the Javascript to the HTML (HyperText Markup Language) already on your page. To be able to do this you need to know the difference between pasting text into a web page and pasting code. To add Javascripts to your page you need to be able to paste code. If you use a web editor where you code the HTML tags yourself then you already know how to add code to your page. If instead you use a WYSIWYG (what you see is what you get) web editor then you will need to locate the option in the program that allows you to paste code instead of text.

The web browser is needed to test your page after you have added the Javascript to check that the page still looks the way that it is supposed to and that the Javascript performs its intended function. If you want to be sure that the Javascript works in multiple browsers then you will need to test it in each browser separately as each browser has its own quirks when it comes to some aspects of Javascript.
Using Pre-Built Scripts

You don't have to be a programming wizard to be able to use Javascript. The reason for this is that there are a lot of programmers out there (myself included) who have already written Javascripts that perform a lot of the functions that you may want to incorporate into your web pages. Many of these scripts are made freely available for you to copy from script libraries for use on your own site. Usually all that you need to do is to follow a series of instructions provided with the script to customize it and then paste it into your web page.

What restrictions are placed on your use of these scripts? Usually not much. In most cases the only restriction is that you only alter those parts of the script that you are told to change in customizing the script for your site. Most scripts contain a copyright notice identifying the original author and the web site from which the script was obtained. These notices must be kept intact when you use scripts obtained in this way.

What's in it for the programmer? Well if someone sees their script on your site and thinks to themselves "What a cool script, I wonder if I can get a copy?" they will most likely view the source code of the script and see the copyright notice. The programmer therefore gets the credit they deserve for writing the script and perhaps more visitors to their own site to see what else they have written.

The biggest problem though with pre-built scripts is that they do what their author wanted them to do which is not necessarily what you want. To resolve this problem you need to either drastically modify the script or write your own. To do either of these will require that you learn to program with Javascript.
Learning Javascript

The two main sources of information if you want to teach yourself to program with Javascript are web pages and books. Both will provide you with a wide range of resources from beginners tutorials through to advanced reference pages. What you need to do is to locate the books or web sites aimed at your level. Start out using books or sites that are aimed at more advanced programmers and a lot of what they are saying will be incomprehensible to you and you will not achieve your goal of learning to program with Javascript.

You need to be particularly careful to select a book or web site tutorial that doesn't assume prior programming knowledge that you haven't got.

If you prefer not being left to figure it out for yourself then the web has advantages over books in that many web sites provide a means for you to contact the author and/or other readers who can provide you with some assistance when you get stuck on some particular point.

Where even that isn't enough and you want face to face teaching then check with your local college or computer store to see if any courses are available in your local area.
Find it Here

There are loads of resources available to help you with whichever course of action you decide to take. If you are looking for pre-built scripts then check out the Script Library. You can also Create Custom Scripts of your own.

As well as an introductory tutorial series to help you Learn Javascript there are also tutorials available to help you with Form Validation and Popup Windows.

A Brief History of Javascript

When the World Wide Web was first created in the early 1990s all web pages were static. When you viewed a web page you saw exactly what the page was set up to show you and there was no way for you to interact with the page.

Being able to interact with a web page - have it do something in response to your actions - required the addition of some form of programming language to "instruct" the page how it should respond to your actions. In order to have it respond immediately without having to reload the web page this language needed to be able to run on the same computer as the browser displaying the page.

At the time there were two browsers that were reasonably popular - Netscape Navigator and Internet Explorer. Netscape was the first to bring out a programming language that would allow web pages to become interactive - they called it Livescript and it was integrated into the browser (meaning that the browser would interpret the commands directly without requiring the code to be compiled and without requiring a plugin to be able to run it). This meant that anyone using the latest Netscape browser would be able to interact with pages that made use of this language.

Another programming language called Java (which required a separate plugin in order to run) became very well known and so Netscape decided to try to cash in on this by renaming the language built into their browser to Javascript. Note that while some Java and Javascript code may appear similar, they are in fact two entirely different languages that serve completely different purposes.

Not to be left behind Internet Explorer was soon updated to support not one but two integrated languages. One was called vbscript and was based on the BASIC programming language and the other was called Jscript and was very similar to Javascript. In fact if you were very careful what commands you used you could write code that would be able to be processed as Javascript by Netscape Navigator and as Jscript by Internet Explorer.

At the time Netscape Navigator was by far the more popular browser and so later versions of Internet Explorer implemented versions of Jscript that were more and more like Javascript. By the time that Internet Explorer became the dominant browser Javascript had become the accepted standard for writing interactive processing to be run in the web browser.

The importance of this scripting language was too great to leave its future development in the hands of the competing browser developers and so in 1996 Javascript was handed over to an international standards body called ECMA who then became responsible for the subsequent development of the language. As a result of this the language was officially renamed ECMAScript or ECMA-262 but most people still refer to it as Javascript.

What is JavaScript

What exactly is Javascript?: Javascript is a programming language that is used to make web pages interactive. It runs on your visitor's computer and so does not require constant downloads from your web site.
Are Javascript and Java the same?: No, they are two completely different computer languages. Only their names are similar.
What do I need to run Javascript?: Javascript support is built right into web browsers. Provided that the visitors to your site are using web browsers that support Javascript (most do) and have Javascript enabled (it is by default) then your Javascript will run.
Do I need to learn Javascript to be able to use it?: No. There are plenty of Javascripts that have already been written that people have made available for you to plug straight into your web page. All you need to know to be able to use such scripts is how to paste the supplied code into the required places in your web page.
What do I need to write Javascript?: Javascript is an interpreted language and so no special program is required to be able to create usable code. Any plain text editor such as Notepad is quite satisfactory for being able to write Javascript. That said, an editor which colourizes the code to make it easier to see what is what makes it easier to find your mistakes but then my Javascript Formatter can reformat your script to make errors even easier to spot.
Can I use HTML instead of Javascript?: No. HTML and Javascript are two completely different things. HTML is a markup language designed for defining static web page content. Javascript is a programming language designed for performing dynamic tasks.
Can I use PHP or some other server side language instead of Javascript?: Perhaps, it depends on where the code needs to run. If it can run before the page loads you can use a server side language. If it has to run after the page has loaded then you must use Javascript as this is the only scripting language supported by all web browsers that support client side scripting.
Does the Javascript go in the same file as the HTML?: It can but your scripts will be more easily reused on multiple pages of your site if you place them in separate files (using a .js extension helps identify them as Javascript). You then just link the Javascript to your HTML by inserting a tag. The same Javascript can then be added to several pages just by adding the appropriate tag into each of the pages to set up the link.

Pattern matching

Regular expressions are a very powerful tool when it comes to being able to perform field validations, compare values, perform substitutions and numerous other tasks that would otherwize require dozens or hundreds of lines of extra code. Unfortunately for those just starting out in programming the way that regular expressions are constructed and what the various parts of the code that you use with regular expressions actually mean is at least an order of magnitude more difficult than most other parts of the programming language.

In this series of tutorials we are going to look at what the codes used in regular expressions actually mean one piece at a time and clear up that confusion. We'll start by looking at how we can use a regular expression to see if one character string contains one or more occurrences of a shorter string. This use for pattern matching is about as simple as regular expressions get and will introduce you to how you can easily code a regular expression test.

var myString = 'the cat sat on the mat';
var re = /at/;
if (re.test(myString))
return 'one or more occurrences of "at" found';

The first thing to notice is that regular expressions have their value contaied between slash characters rather than placing them in quotes. Javascript knows when we define an object this way that we are creating a regular expression object. In this example we have defined a regular expression object called re that will process using the character string "at".

We can perform a simple pattern match to see if some text contains this character string by using the test method that belongs to the regular expression object. This method will return true if a match is found for the regular expression within the passed text and false if no match is found. In our example there are several occurrences of "at" within the text and so our call returns true.

Our regular expression in this example is a simple text string of two particular characters. In future tutorials we will see how we can substitute special symbolds that can match to particular types of characters that make using regular expressions for pattern matching a very powerful tool.

Mastering Regular Expressions

The Bottom Line

The author really understands regular expressions and provides complete coverage on both how to use them and how they actually work. Some of the examples could have been better thought out though.
Pros
  • Covers most languages that support Regular Expressions
  • Explains how they work as well as how to use them
  • Covers all of the variations that different languages use
Cons
  • Some examples demonstrate a lack of knowledge of HTML
  • The book doesn't mention Javascript

Description

  • Third Edition: Published August 2006
  • 515 page paperback
  • Published by O'Reilly Media
  • ISBN 0-596-52812-4
  • Understand your data and be more productive
  • Author Jeffrey E.F. Friedl

Guide Review - Mastering Regular Expressions

There are quite a few different languages that support Regular Expressions and the author discusses all of them except for Javascript. While this key language has been omitted from the book much of what the book covers is still of great use to those who want to use Regular Expressions with Javascript although the information on which parts do and don't work in different languages only covers the other languages that support regular expressions.

Some of the examples that the author uses also demonstrate that while he has an indepth undertanding of regular expressions he does not understand HTML as several of his examples discuss such things as how to insert paragraph separators (something HTML doesn't have- it uses paragraph containers).

If you want a greater understanding of what can be done with regular expressions and how they work then this will be a really useful book for you to read.

Compiling Regular Expressions

In the article Regular Expressions in VB.NET, I show the basics of coding regular expressions in VB.NET. Regular expressions are a 'language in a language' with a history that starts before Visual Basic or even just B.A.S.I.C. and they're used in a lot of programming languages. For this article, I use the "telephone number" RegEx from the article above. Read that article for a more detailed explanation of why it works.

Although they're very handy by themselves, regular expressions can be even more useful as compiled DLL modules for all the same reasons that you compile anything: speed, security, and a better way to organize code in libraries.

Because it's a 'language in a language', there's no standalone compiler for RegEx in VB.NET. Instead, there's a static method that is part of the normal RegularExpressions namespace. The method is called CompileToAssembly and you will usually call it with two parameters which, naturally enough, are the 'source code' input and the 'compiled assembly' output. (There are also overloaded methods that let you include custom attributes that can be passed to the compiled DLL. The article Attributes in VB .NET explains what attributes are in VB.NET.)

To see just how much improvement is possible using compiled regular expressions, this article will show how to compile one. Then the StopWatch component of the System.Diagnostics namespace will be used to compare how fast a regular "inline" execution of the RegEx is versus the same compiled RegEx.

First, we have to compile the RegEx. This requirement will probably result in the creation of a utility if you use very many compiled regular expressions. Here's the way I did it. (Arguments in the event Sub's are not shown in this article to save space.)

Private Sub CompileRegEx_Click( ...
Dim myRegexString As String = _
"^1?\s*-?\s*(\d{3}|\(\s*\d{3}\s*\))" & _
"\s*-?\s*\d{3}\s*-?\s*\d{4}$")
Dim RegExNameSpace As String = "myRegExNS"
Dim RegExType As String = "myRegExType"
Dim RegExIsPublic As Boolean = True
Dim RegExAssembly As New _
System.Reflection.AssemblyName("myRegExAssembly")
Dim CompileRegExParms As New RegexCompilationInfo( _
myRegexString, _
RegexOptions.Compiled, _
RegExType, _
RegExNameSpace, _
RegExIsPublic)
Dim CompileRegArray() _
As RegexCompilationInfo = {CompileRegExParms}
Regex.CompileToAssembly(CompileRegArray, RegExAssembly)
End Sub

Notice that the actual RegEx is now just a string (instead of being declared as a RegEx as it was in the article referenced earlier). That's because it's passed to the RegexCompilationInfo to be saved as a string property. The illustration below shows the property displayed in the MsgBox.

--------
Click Here to display the illustration
Click the Back button on your browser to return
--------

In addition to the actual text of the RegEx, we need to declare ...

  • The namespace that the compiled RegEx will be in: myRegExNS
  • The name of the type of the compiled RegEx: myRegExType
  • Whether the compiled Regex will be public or not: RegExIsPublic
  • The name of the assembly (the compiled DLL) for the RegEx: myRegExAssembly

Most of this information is simply passed to the New constructor for the RegexCompilationInfo object. The assembly name is used when the RegEx is compiled.

One additional detail needs doing. The Regex.CompileToAssembly method actually expects an array of RegexCompilationInfo objects, not just one. The assumption is that you will compile a lot of different regular expressions into the same DLL assembly. That's why this statement is necessary:

Dim CompileRegArray() _
As RegexCompilationInfo = {CompileRegExParms}

Once all this is done, compiling is just a method call:

Regex.CompileToAssembly(CompileRegArray, RegExAssembly)




Using the compiled RegEx is just like using any other object. Add a reference to it using the Project Properties dialog:

  1. Right-click the project and select Add Reference...
  2. Browse to the location of the assembly and select it.

--------
Click Here to display the illustration
Click the Back button on your browser to return
--------

Using a compiled RegEx is the same as any other object.

Dim myCompiledRegex As New myRegExNS.myRegExType
Dim RegExResult As Boolean
RegExResult = myCompiledRegex.IsMatch("String to Match")

But just how much will this speed up your application? Let's find out.

I borrowed the timing code from my StringBuilder article and simply changed the variables a bit and had this running in a few minutes ...

Imports System.Diagnostics
Imports System.Text.RegularExpressions

Public Class CompiledRegEx
Dim InlineTimeSpan As Integer
Dim CompiledTimeSpan As Integer
Dim LoopLimit As Integer
Dim PhoneNum(9999) As String
Dim I As Integer

Private Sub TimeEm_Click( ...
If UseInline.Checked Then UseInlineTest()
If UseCompiled.Checked Then UseCompiledTest()
CalcImprovement()
End Sub

Private Sub UseInlineTest()
Dim myRegexString As New Regex( _
"^1?\s*-?\s*(\d{3}|\(\s*\d{3}\s*\))" & _
"\s*-?\s*\d{3}\s*-?\s*\d{4}$")
Dim RegExResult As Boolean
Dim myStopwatch As Stopwatch = New Stopwatch
Dim myTimeSpan As New TimeSpan
myStopwatch.Reset()
myStopwatch.Start()
For I = 0 To LoopLimit
RegExResult = _
myRegexString.IsMatch(PhoneNum(I).ToString)
Next
myStopwatch.Stop()
myTimeSpan = myStopwatch.Elapsed
InlineTimeSpan = myTimeSpan.Milliseconds
UsingInline.Text = myTimeSpan.ToString
End Sub

Private Sub UseCompiledTest()
Dim myStopwatch As Stopwatch = New Stopwatch
Dim myCompiledRegex As New myRegExNS.myRegExType
Dim RegExResult As Boolean
Dim myTimeSpan As New TimeSpan
myStopwatch.Reset()
myStopwatch.Start()
For I = 0 To LoopLimit
RegExResult = _
myCompiledRegex.IsMatch(PhoneNum(I).ToString)
Next
myStopwatch.Stop()
myTimeSpan = myStopwatch.Elapsed
CompiledTimeSpan = myTimeSpan.Milliseconds
UsingCompiled.Text = myTimeSpan.ToString
End Sub

Private Sub CalcImprovement()
Try
Improvement.Text = _
CStr((InlineTimeSpan / CompiledTimeSpan))
Catch ex As Exception
Improvement.Text = ""
End Try
End Sub

Private Sub CompiledRegEx_Load( ...
Dim PhoneNumSuf As Integer = 0
Dim PhoneNumPre As String = "123-555-"
LoopLimit = CInt(NumberOfIterations.Text) - 1
For I = 0 To LoopLimit
PhoneNum(I) = _
PhoneNumPre & I.ToString.PadLeft(4, "0"c)
Next
End Sub
End Class

The result showed a very significant improvement of about 30 to 50 percent, but frankly, I expected more



After examining the code for a while, I wondered if VB.NET was optomizing the RegEx by reusing a version 'compiled' in realtime. To test this guess, I coded a new version that forced the RegEx to be declared for every iteration of the test loop by coding the loop before the call rather than after.

Imports System.Diagnostics
Imports System.Text.RegularExpressions

Public Class CompiledRegEx
Dim InlineTimeSpan As Integer
Dim CompiledTimeSpan As Integer
Dim LoopLimit As Integer
Dim PhoneNum(9999) As String
Dim I As Integer

Private Sub TimeEm_Click( ...
Dim myStopwatch As Stopwatch = New Stopwatch
Dim myTimeSpan As New TimeSpan
myStopwatch.Reset()
myStopwatch.Start()
If UseInline.Checked Then
For I = 0 To LoopLimit
UseInlineTest(I)
Next
End If
myStopwatch.Stop()
myTimeSpan = myStopwatch.Elapsed
InlineTimeSpan = myTimeSpan.Milliseconds
UsingInline.Text = myTimeSpan.ToString
myStopwatch.Reset()
myStopwatch.Start()
If UseCompiled.Checked Then
For I = 0 To LoopLimit
UseCompiledTest(I)
Next
End If
myStopwatch.Stop()
myTimeSpan = myStopwatch.Elapsed
CompiledTimeSpan = myTimeSpan.Milliseconds
UsingCompiled.Text = myTimeSpan.ToString
CalcImprovement()
End Sub

Private Sub UseInlineTest(ByVal I As Integer)
Dim myRegexString As New Regex( _
"^1?\s*-?\s*(\d{3}|\(\s*\d{3}\s*\))" & _
"\s*-?\s*\d{3}\s*-?\s*\d{4}$")
Dim RegExResult As Boolean
RegExResult = _
myRegexString.IsMatch(PhoneNum(I).ToString)
End Sub

Private Sub UseCompiledTest(ByVal I As Integer)
Dim myCompiledRegex As New myRegExNS.myRegExType
Dim RegExResult As Boolean
RegExResult = _
myCompiledRegex.IsMatch(PhoneNum(I).ToString)
End Sub

Private Sub CalcImprovement()
Try
Improvement.Text = _
CStr((InlineTimeSpan / CompiledTimeSpan))
Catch ex As Exception
Improvement.Text = ""
End Try
End Sub

Private Sub CompiledRegEx_Load( ...
Dim PhoneNumSuf As Integer = 0
Dim PhoneNumPre As String = "123-555-"
LoopLimit = CInt(NumberOfIterations.Text) - 1
For I = 0 To LoopLimit
PhoneNum(I) = PhoneNumPre & I.ToString.PadLeft(4, "0"c)
Next
End Sub
End Class

This time, the results were much closer to what I expected: about 7 1/2 times faster!

--------
Click Here to display the illustration
Click the Back button on your browser to return
--------

The lesson here is that if you can avoid re-executing the statement that declares your RegEx, it will add more to your execution speed than even compiling the RegEx.

expression tricks3

RegEx is built into VB.NET, but you should reference the right namespace to use it. When you use RegEx, add an Imports statement:

Imports System.Text.RegularExpressions

Here's a quick example showing how to use RegEx. MatchCollection and Regex are objects in the RegularExpressions namespace. You can find complete documentation on them at MSDN. This segment from an About Visual Basic tutorial tells you how to find information there.

--------

Click the Back button on your browser to return
--------

Dim myMatches As MatchCollection
Dim myRegex As New Regex("\w+")
Dim t As String = _
"Introduction to Regular Expressions " & _
"in Visual Basic"
myMatches = myRegex.Matches(t)
' Search for all the words in a string
Dim successfulMatch As Match
For Each successfulMatch In myMatches
Debug.WriteLine(successfulMatch.Value)
Next

Add this code to a Button event subroutine and it will display each of the words in the string in the Immediate window.

Introduction
to
Regular
Expressions
in
Visual
Basic

The "regular expression" is the string in myRegex.

We can also try out the "telephone number" example shown earlier. To check a (USA style) phone number, this code will display True in the Immediate window.

' Check a (USA style) telephone number
Dim myRegex As New Regex( _
"^1?\s*-?\s*(\d{3}|\(\s*\d{3}\s*\))\s*-?\s*\d{3}\s*-?\s*\d{4}$")
Dim t As String = _
"1-800-555-1212"
Debug.WriteLine(myRegex.IsMatch(t))

"800-555-1212" also works, But an area code is required so just "555-1212" returns False.

To start writing your own regular expressions, let's try something a little easier. Validating a USA social security number is both useful and a good starting exercise. Once you understand how to do it, you'll be part of the way through the learning curve for the telephone number expression above.

A SSN is a number that must be in the pattern:

999-99-9999

or

999999999

Matching just 9 numbers (the second case)

If we were not going to test for the dash characters, it would be easy. The expression would simply be:

\d{9}

The \d metacharacter matches any number from 0 to 9. The {9} matches 9 of them. (You often see a different expression that does the same thing: [0-9]. This is a character group covering the range from 0 to 9.)

This works great ... except ... if there are 10 numbers, it still matches (since it matches the first 9). We need more qualification. There are two more metacharacters that will work here: "^" (caret) and "$" (dollar sign). Used in this context, the caret will match characters at the left side of a string. (Used in other ways, the caret means something completely different. This is one of the things that can make RegEx so complicated.) The dollar sign will match characters at the right side. So, if we want only 9 numbers, match at both the left and right and it will restrict the match. This makes our evolving RegEx ...

^\d{9}$

Matching With And Without Dashes

But what about the dashes? Simply put the dash in where it belongs as a character by itself. Then adjust the counting of the numbers in the three groups. This will match a "traditional" social security number:

^\d{3}-\d{2}-\d{4}$

But now it no longer matches a number without the dashes! To solve this problem we use the "?" (question mark) metacharacter. When a question mark follows a character or character group, it means that it will match 0 (zero) or 1 (one) time - in effect, making it optional. This is the final touch for our SSN RegEx expression:

^\d{3}-?\d{2}-?\d{4}$

Regular expressions are one of those topics, like programming itself, that you can learn more and more about and still not know everything. To make things more complex, there's no "regular expression" standard and the way it's implemented will be slightly different in different software implementations. (Java will evaluate the same RegEx differently than VB in some cases.) There's more of an "understanding" in the programming community about what a RegEx means, not a clear definition.

expression tricks2

RegEx is exactly the same idea, but the idea has been developed to allow just about any kind of text searching you can imagine to be done. Andrew Watt wrote an 800 page book ( that he called, Beginning Regular Expressions. I wonder how many pages it it would take to write the "Advanced" version.

The big problem with RegEx's is that they are sort of a "write-only" language. A RegEx that does something meaningful, (such as this example to match patterns for US telephone numbers (credit to author Jesse Sweetland) ...

^1?\s*-?\s*(\d{3}|\(\s*\d{3}\s*\))\s*-?\s*\d{3}\s*-?\s*\d{4}$

... can be hard for anyone to figure out how it works after it's written. Don't be fooled because this is just one line of code. It might take even an experienced programmer quite a while to craft something like this. (I'll use this RegEx in some VB code in a few paragraphs.)

For this reason, there are a lot of utilities that you can download that help you figure out what a regex is doing. Some examples:

  • RegexBuddy from JGsoft
  • RegexDesigner .NET from Chris Sells

Historical Sidetrack ...

A lot of people (myself included) get confused right away because we don't even understand why these things are called 'regular expressions'. Just to clear this out of the way so we can get to the important stuff, the term was first used by the American mathematician Stephen Kleene. For him, it was a branch of mathematics and he figured out math rules that make it work. For programmers, it's just a name, so call them "widgets" or "thingies" if it will help you understand better.

But if you want to get geek points for knowing obscure stuff, the '*' character that we usually call a "wildcard" is sometimes called a Kleene star in academic circles and - here's a good one - Kleene pronounced his last name klay'nee. His son, Ken Kleene, wrote: "As far as I am aware this pronunciation is incorrect in all known languages. I believe that this novel pronunciation was invented by my father." Dr. "Clay Knee" must have been a geek of the first water, to be sure!




Regular expression tips

What is RegEx all about?

Regular Expressions - also known as "RegEx" - are strings of text used to match patterns in other strings. The classic example is a search string that uses "wild cards" such as an "*" or "?" (which are also used in "regular" regular expressions). VB.NET has much better support for RegEx than VB 6. If you're looking for information about how to use it in VB.NET, About Visual Basic has that too.
To get the basic idea behind RegEx, open a "Search" in Windows Explorer to look for a file on your computer. Enter "*.ico" into the "All or part of the file name" text box (the "word or phrase" text box doesn't support wild card characters). You should get a list of hundreds of "icon" files if you search your whole computer. The "*" wild card will "match" any file name and the ".ico" will "match" icon files that end in just those characters.

Part 4: Other Sources for Learning VB 6

One really great advantage of deciding to learn VB 6 is that the world has had time to develop top notch tutorials. There are really more of them than you have time! We're here to help you solve that problem by selecting the good ones so you don't have to spend your time on the others. You can find a concise set of the best pages here that will get you up to speed on VB 6. Go through this list of pages thoroughly, and then print a diploma for yourself. You're a VB 6 programmer!

Moving Up to Objects
At about this time, a few experienced programmers reading this will be shouting, "VB 6 is not object oriented!!"

Mmmmmm ... Yes it is.

This has got to be one of the great religious struggles in programming. Although the wars don't rage like they once did, some people have rigidly defined definitions of exactly what is, and is not, object oriented and according to those definitions, VB 6 and predecessors do not make the grade. Others, including me, take the view that "object oriented" is a concept, and not a set of rules. VB 6 is clearly object oriented in concept.

Visual Basic and Data
The first thing you need to know about is databases and one of the best to start with is Access, Microsoft's database for non-server environments. The About.com 'Databases' site has an excellent article about Access here.

When you have created (or borrowed ... several great example databases are available along with VB and Access from Microsoft) a database, the next thing to do is use the Data Control object to read and write the data. An article about how to do that with Microsoft's latest data technology, ADO, can be found here.

Visual Basic and Active Server Pages
Another more advanced technology that you can use with VB 6 is called Active Server Pages, or ASP. This is the technology that allows you to run your VB 6 system on an IIS web server and server HTML pages controlled by your programming over the web. You can find an introduction to doing that in a VB 6 environment here.

When VB.NET was introduced, Microsoft put millions into the advertising budget because they were very worried about the competition. They really were not sure that .NET could measure up. The competition is VB 6!

Part 3: Finishing the Two Button Form

In the previous page, we actually completed the design of the form for our project ... which only consisted of dragging two command buttons to the form. In this page, we change their names, add the event code for both buttons and actually run the program.
Steps 4 and Step 5
Click the first Command Button to select it. Open the property window and change the Name property to CommandA. Change the Caption to A.
Select the second Command Button from the drop down window at the top of the property window and then change the Name property to CommandB. Change the Caption to B.

The new thing in this step is 'Open the property window'. Remember the 'right click context menu' from the previous page? Try right clicking the first command button and you will see ...

Click 'Properties' at the bottom to open the window. Then click the 'Name' property in the first column and change the value in the second. We do this because we want to use unique names in our program code to refer to this object. Visual Basic will do it automatically (it already has) but it's hard to keep track of a series of objects with names like 'Command1', 'Command2', and so forth. You might also notice that the Property window is dockable and resizable. It's been undocked and resized below:

Steps 6, 7, 8, and 9
Double click the first 'Command Button' object in the form to open the code window for that button.
Enter the code,

Msgbox "You clicked Button A"

after the automatically entered code

Private Sub CommandA_Click()

Double click the second 'Command Button' object in the form to open the code window for that button.
Enter the code,

Msgbox "You clicked Button B"

after the automatically entered code

Private Sub CommandA_Click()

Notice that a subroutine has already been entered into the code window automatically. VB 6 helps out as much as it can! All you have to do is enter your code inside the subroutine. It's worth knowing that all of the code is actually saved in the form object. VB has to organize the files for your project and that just happens to be where it is. If you have independent module code (code that might be used anywhere your program, rather than just for one particular object and event), it's saved in a different object. Another thing to notice is the 'naming convention' used for the subroutine:

CommandA_Click

This is always the same. The first part is the name of the object. The second part is the event. You can't change this name or VB won't know where to find your event code. Let VB assign these names and leave them alone.

Steps 10 and 11
Click the 'Run' button in the toolbar at the top of the VB 6 development environment window to execute the program.
Click either button A or button B and observe the fruits of your labor!

The only confusion factor here might be, "Where is this 'Run' button?" The answer is, "Right Here ..." (You can also find this on the 'Run' menu.)

If you still think you need some more help getting up to speed, check out some of the other web pages in the links on the next page.

Part 2: The Two Button Form In Detail

In the previous page, we went through the 'Two Button Form' at Internet speed. We're going to look at it in detail and explain all the steps this time.

Step 1 and Step 2
Start Visual Basic. Usually, 'Start > Programs > Microsoft Visual Studio > Microsoft Visual Basic 6.0'.
Click the default "Standard EXE" icon and then click the "Open" button.

You should see the opening dialog window as explained in Learning Visual Basic. Check that page out for more.

Step 3
Drag a 'Command Button' from the 'Toolbox' to the form and drop it. Drag another one to the form and drop it.

The VB 6 development environment is designed to let you constantly change the components that are visible so you can work with only those windows that apply to the problem at hand. The 'ToolBox' is one of those components and may, or may not, be visible in your system. The 'Toolbox' looks like this: (The tools that are in the toolbox can change too!)

If you can't see the toolbox, look for it in the 'View' menu. And notice that several other components can be turned on and off there, too. Some that you will use are:

  • Project Explorer
  • Immediate Window
  • Locals Window
  • Watch Window

Another thing to know is that VB 6 uses the right-click 'context menu' a lot. Right click 'Form1' for example and notice the options there. This is the fastest way to switch between viewing an object (like Form1) and the code in that object.

Part 1: VB 6 is The King

Although VB.NET is gaining ground fast, VB 6 remains a very popular programming environment. But even if it wasn't as great as it is, if you're new to Visual Basic and you have a copy available, it's still a great place to start learning about programming!

The only real problem with using VB 6 is that you really can't buy a copy today. Microsoft just isn't selling them anymore. There's no reason why you can't continue to use VB 6 for as long as you want to however. Microsoft will support the VB 6 environment even on the very latest Vista operating system scheduled to be introduced in 2007.

One reason VB is so great for learning is that the original BASIC ("Beginner's All purpose Symbolic Instruction Code") was designed as a language to teach people how to program by Kemeny and Kurtz at Dartmouth College w-a-a-a-y back in 1963. A lot of very talented programmers think that VB 6 is still the best development environment. You can check out their reasons here and here. Or perhaps you're reluctant to pay the new, enhanced prices that Microsoft is asking for .NET software. Whatever your reasons, it's clear that VB 6 is going to be around for a good while longer. You can invest in learning how to be an expert programmer using VB 6 and be confident that you're not wasting your time!

Still not sure? Here's what the legendary VB Guru Dan Appleman has to say about the idea that you have to switch to VB.NET immediately:

These ideas are basically nonsense. ... The magnitude of the change is such that the transition to VB.NET is likely to be measured in years rather than months -- and for some applications, it may not make sense to switch at all.

Learning VB 6

In the 'Essentials' topic Learning Visual Basic, a program that uses one form with two command buttons was introduced.

We're going to go through the complete steps to create this.
First ... in rapid fire ... the steps.
Then ... a more complete explanation.

  1. Start Visual Basic. Usually, 'Start > Programs > Microsoft Visual Studio > Microsoft Visual Basic 6.0'.
  2. Click the default Standard EXE icon and then click the Open button.
  3. Click the Command Button icon in the Toolbox. Draw two buttons on the form by clicking and dragging.
  4. Click the first Command Button to select it. Open the property window and change the Name property to CommandA. Change the Caption to A.
  5. Select the second Command Button from the drop down window at the top of the property window and then change the Name property to CommandB. Change the Caption to B.
  6. Double click the first Command Button object in the form to open the code window for that button.
  7. Enter the code, Msgbox "You clicked Button A" after the automatically entered code Private Sub CommandA_Click().
  8. Double click the second Command Button object in the form to open the code window for that button.
  9. Enter the code, Msgbox "You clicked Button B" after the automatically entered code Private Sub CommandB_Click().
  10. Click the Run button in the toolbar at the top of the VB 6 development environment window to execute the program.
  11. Click either button A or button B and observe the fruits of your labor!

Whew!!! Continue on to the next page to do this a little slower.