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.