Visual Basic was created to allow programmers to write real applications, real fast. Prior to the release of Visual Basic 1, writing a Windows application was hard work, requiring a lot of very low-level programming knowledge just to get a simple window to appear. Visual Basic removed this level of "under-the-hood" complexity by automating a good deal of the difficult nuts-and-bolts programming that was required to be able to write even the simplest of Windows applications. Procedures such as creating and placing windows, selecting fonts by which to output text to a control, or defining an event such as a button click--though very difficult things to do in a low-level language such as C--are relatively simple in Visual Basic. However, although VB frees the programmer from the more mundane chores of Windows programming, it does not relieve the programmer from the responsibility to follow good software design and programming practices.
An analogy can be drawn here: A programmer is to Visual Basic as a cabinetmaker is to power tools. While a power tool can make the labor of cabinetmaking easier, mere use of the tool does not guarantee that the cabinetmaker will make a good cabinet. The use of the tool is only as good as the cabinetmaker's ability to make and follow a schematic, select the appropriate materials, and execute the fundamental skills of cabinetmaking.
The same can be said of writing programs in Visual Basic. Although Visual Basic is a very powerful and easy-to-learn tool, programs created with Visual Basic are only as good as the design and implementation skills of the programmer. Visual Basic makes programming easier, but it does not necessarily make programmers better. Being an effective software developer means having a clear idea of what program you want to write, who you want to write it for, and how you want to do it. Many times, paying attention to the needs, expectations, and habits of the user of your software is a trivial afterthought in the software development process. This tendency is self-defeating because, in most cases, intrinsic ease of use determines the long-term success of your code.
The process of software development can be broken up into three phases (see Table 19.1).
Phase | Activities |
Pre-production | Identify your users Analyze their needs and skills Determine the features they require Prioritize features Create a program specification Create a schematic of the program |
Production | Divide the work among developers Write code and build objects Debug and test your code Perform usability tests Correct bugs and address usability issues |
Post-production | Prepare online help and end user manuals Document program for future maintenance Prepare program for deployment Evaluate program and process for future versions |
Understanding the activities and dynamics of each of these phases is important to the overall efficiency of your development effort and the quality of your end product.
The pre-production phase of developing a Windows application is where your product is defined and specified. In pre-production, you draw up the blueprint upon which your product will be built. In this phase, you decide what is the purpose of the product, what are its features, and--of those determined features--which version of your product will implement a given feature set.
In pre-production, you create a user profile. The purpose here is to gather as much information as possible about the users of your program. For instance, you determine whether your intended users are comfortable with Windows, thus requiring little elementary support. If your users have never used a computer before, your program will require a good deal of on-screen instruction.
Localization issues are also identified during this phase. Will your product be released only in the U.S. version of English? Will it eventually require other languages? Additionally, consider where and when the customer will run your program. Will it be a point-of-sale system that handles thousands of daily transactions, or will it be used only once a month?
For example, suppose you are writing an Internet application with a Login page. If you are expecting a large number of hits (or hackers), loading your entire program into memory for every login attempt is probably not a good idea. One solution would be to design a fast and small Login object, so you don't bog down the server. It is best to address issues like these at the beginning of the development process where change is cheap, rather than at the end of the process where change is very, very expensive.
TIP: It is always most cost effective to correct a mistake or make a change to a program feature in the pre-production phase. Making a change at a later point in the development process is costly in terms of time and money. This is because the program must be re-specified, re-coded, re-tested, and re-documented.
The production phase of the development process is where you take the product specification prepared in pre-production and turn it into code. In addition, you create media and other resources that your code might require. In this phase, you determine the optimal language in which to code. (Since this is a book on Visual Basic, for all intents and purposes the optimal language is Visual Basic. However, keep in mind that this might not always be the case. Even VB has its limitations and misapplications.)
If you are working within a group of programmers, production is where you divide up the work and do build (or version) control. A build is the process of taking all the pieces of code that each developer is working on and compiling the software. Depending on the testing requirements of your project, you might want to have a daily build scheduled. Because there can be several builds during the development process, there must be a system in place so that each programmer can submit the latest version of his or her code. There is a variety of version control software available to do this, including Microsoft Visual SourceSafe, which is included with the Enterprise Edition of Visual Basic 5.0.
System testing is the process of testing code for bugs, usability, and compliance to specifications. The testing process is also done within the Production phase. There are two major schools of thought concerning testing methods, and both are worth mentioning here.
One method of testing is called waterfall testing (see Figure 19.1). In the waterfall method, the testing process is considered to be separate from the programming part of the software development process. Waterfall testing requires that, prior to testing, all the code is written to specifications. Then that code is sent to the tester for testing. After the testing is completed, the results are sent back to the developers to make the necessary code corrections and modifications.
FIG. 19.1
Waterfall testing requires that most testing take place at the end of the
production phase.
Another testing method is called iterative testing (see Figure 19.2). In this method, testing is considered to be part of the programming process. As the programmer completes a discrete set of procedures, he is continually sending his completed work to the tester for inspection and response. While the iterative method might seem like nothing more then a lot of little waterfall tests, it is not. In the iterative testing method, the tester is included in and consulted about the development process from as early as the pre-production phase. In the waterfall method, the tester is brought in well toward the end of the production phase.
Both methods work, and both have their virtues and shortcomings. The waterfall method enables programmers to quickly move from task to task, concentrating on code. However, bugs that the developer overlooks can create their own waterfall of problems when testing finally occurs, especially if the bug happens to be at an early point of the program. And although an iterative approach can provide quicker feedback, requiring the developer to spend a lot of time testing can slow the entire process. One important thing to remember is that any given testing method does not excuse the programmer from testing his own procedures and functions.
FIG. 19.2
Iterative testing requires that testing take place throughout the production
phase.
The post-production phase of software development is where built software is documented, prepared for deployment, and evaluated for future version releases. This process involves all the steps necessary before releasing the software to the public. In the post-production phase, you create both user and programmer documentation, as well as installation media. Beta testing and user feedback can occur during and after this process.
Documentation After your code is acceptably bug-free and compliant to specifications, you must write the documentation for it. The scope of the documentation includes not only the online help and manuals for the end user, but also the blood-and-guts manuals for the people who will be maintaining your code in following versions. The section "Avoiding Programming Pitfalls" later in this chapter discusses some techniques that you can use to make your code easier to document.
CAUTION: Unfortunately, documentation is one area that people often skimp on. This is never a good idea. Just remember, it might be you who has to maintain the code--and your memory might not be as reliable as you think!
Deployment As your program is being documented, you can also prepare it for deployment. Deployment is the act of distributing your program to others. Whether you use a modest floppy disk in an envelope or a more extravagant shrink-wrapped CD-ROM release, you want to put as much effort into your deployment as you did with programming.
NOTE: Visual Basic programs can be deployed several ways, including CD-ROM, floppy disks, or a network. Distribution via the Internet is now a reality as well. See Chapter 17, "Managing Your Projects" for a detailed discussion on creating Setup programs.
See "Using the Setup Wizard," Chapter 17
First, you need to use the Setup Wizard or another setup utility to create an installation process for your program. After you have created this installation process, you must thoroughly test it on as many different systems as possible. You might write the most sophisticated piece of software in the world, but if its setup program doesn't install your program properly, your labor is lost.
If you are shipping your program on floppy disks, you should label each disk clearly, avoiding handwritten labels in favor of ones printed on a laser printer or by a professional printer. Using Disk X of Y tagging on the labels is a good practice to follow. For an end user, there are few things more frustrating than trying to install a piece of software only to find out that you are missing a disk.
However, due to the increasing size of Windows applications, it would not be too bold a prediction to say floppy disk installations are going the way of the dinosaur. Program setup can be an incredibly time-consuming process if the install files must be broken into a large number of 1.44M disk-sized chunks. On the other hand, a blank CD can hold about 650 megabytes of data, and the cost of CD recorders and media has decreased considerably in recent years.
Whatever media you use, label it with clear and brief instructions. If your application is built around components that require their own setup (such as ODBC), try to integrate the setup programs as much as possible. Users will appreciate setups that are simple, with a single icon or command. If distributing via CD-ROM, you might want to include an AUTORUN.INF file, which allows your setup program to start automatically. Also, offer a clear, noticeable message in the deployment package informing the user what to do in the event of difficulty. These things are important and have definite impact on how the quality of your work is perceived.
CAUTION: Files copied from CD-ROM to hard disk have the default file attribute of read-only. You cannot write to them. This can cause problems if your program is deployed with files to which it must write--for example, .INI files or database files. When testing your deployment, check to make sure that your setup program removes the read-only file attribute from the files it copies from CD-ROM.
Evaluation and Future Versions At the end of every software development process is a period where you look over what you have done to determine how to do it better on the next version. Next version? That's right, because most software gets revised, no matter how small the project. As an example, take the Internet browser market, which releases new browser versions with an almost nauseating frequency. As you were developing your project, without a doubt you came across problems. And, as you solved these problems, you probably said to yourself that the next time you did this, you would do so and so, in such and such a way. Mistakes are things from which we learn, and you would do well to anticipate applying what you have learned from your errors to a future version. Make sure to document your thoughts as you get them, for easy "memory retrieval" later. Most software is developed under strict time constraints. No person or enterprise can afford to take forever to produce a functional piece of code. As a result, it is often not possible to implement every specified feature in a given release. Therefore, planning to implement features over progressive versions is a viable development strategy.
TIP: As you program, keep notes of ideas you have for future versions. Remember also (although it might make you snarl) that part of a programmer's job is being a salesperson. The decision to upgrade to a new version of Visual Basic is a perfect example. While the developer sees a cool and exciting programming tool, his boss might just see an expense. Do not be afraid to write small prototype programs or mocked-up forms to show others what is possible. This is sometimes known as a proof-of-concept.
The evaluation of real-life use of your code happens in the post-production period. The true test of a software product's effectiveness and usability is the test of time. No laboratory condition can ever adequately anticipate every nuance of user interaction. It is only by deploying your program, supporting your program, and eliciting the end users' responses that you can accurately evaluate what works and what doesn't.
Software programs are like cars: the more predictable and sensible they are to use, the easier it is to get where you want to go.
Although the Windows operating system has set some standards regarding graphical user interface design--and VB has made programming for Windows a whole lot simpler--there is still a good deal of unpredictable and improper use of Windows components (menus, buttons, list boxes, combo boxes, and so on). This inconsistency defeats the fundamental purpose of the graphical user interface idea--to make operating a computer a more productive, enjoyable, and less frustrating experience for the user.
Do not think that providing a consistent, predictable graphical interface for your program requires you to forego creativity in any way. Take the active toolbar (or coolbar) used first in Microsoft Internet Explorer. Although it broke standards regarding the look of Windows toolbar buttons, it was a great idea and set the standard for the Office 97 toolbars.
Although designing a form in Visual Basic is a simple thing to do, doing it well is not that easy. Good form design involves more than just inserting controls and programming events. To make a well-designed form, you should understand the form's purpose, how it is going to be used, when it is going to be used, and its relationship with the rest of the program.
Let's take a look at the form frmSettings (FRMESET.FRM) in Figure 19.3. The purpose of this form is to set the display attributes for another form. This form suffers from a number of poor design choices that prevent it from effectively achieving its full functionality.
This form is in the project EVIL.JOT.VBP, which somes on the CD-ROM accompanying this book.
FIG. 19.3
The code behind the pictured form might work flawlessly, but it leaves much
to be desired in terms of layout.
The first item for correction is the choice of setting the form's BorderStyle property to Sizable. Should the user resize the form either by intention or mistake (double-clicking the title bar is not an uncommon accident), the form does not resize or reposition the controls to accommodate the new form size (see Figure 19.4). Forms that are sizable are generally used in instances where the user needs a window of varying size to accomplish something--for example, Word's document windows or Paint's drawing window. To correct this problem, set the form's BorderStyle property to Fixed Single or Fixed Dialog.
See "Form Properties Revisited," Chapter 4
TIP: To provide basic re-sizing capabilities, you can place code to move controls around on a form and alter their dimensions in the form's Resize event. For example, the lineIf frmMain.Width > 300 Then lstUserList.Width = frmMain.Width - 300could be used to always keep a list box sized to 300 twips less than the form width, as long as it doesn't result in a negative width.
FIG. 19.4
The controls are not resized or repositioned when the form is resized. The
form's BorderStyle property should be set to Fixed Single or Fixed Dialog.
Another mistake is the initial size and location of the form. It completely covers the form whose attributes are to be set (refer to Figure 19.3, in which the primary form is completely hidden behind the settings form). An analogy would be if Microsoft Word's Find window covered up your entire document. To remedy this flaw, the form should be repositioned so that when it appears, at least a portion of the form to be affected is still showing.
Notice too that the form suffers from poor labeling. The designer is assuming that the user intuitively knows what this form is about, what the function of the label control is, and how each button affects the overall program.
Probably the biggest cause for concern with regard to this form's design is the almost arbitrary use of space and the inconsistent placement of buttons and labels on the form. When it comes to the size of a fixed size form (a.k.a. a dialog box), the rule of thumb is "less is best." You want to allow the form to take up no more real estate than it needs, but not to make it so small that controls are congested and text is illegible.
See "Setting Up the Dialog Box Form," Chapter 6
You should also organize the placement of controls according to functionality. In the frmSettings form, separating the Font Style button from the Background Color button is confusing and causes a lot of unnecessary mouse movement activity. Positioning the Font Style and Background Color buttons together in one group and the OK and Cancel buttons in another wouldcreate distinct areas of functionality that the user would find more organized and memorable.
Taking into account the pitfalls discussed here, look at Figure 19.5. This is an illustration of the improved form, frmSettngs (FRMSET.FRM), which is part of the Visual Basic project GOODJOT.VBP. Notice the reduced size of the form, the change of the form's BorderStyle property, the reorganization of the form's buttons, and the inclusion of a frame to provide a sense of functional unity and descriptive labeling.
FIG. 19.5
Notice that in the improved form pictured here, controls have been grouped
according to their functionality.
Another important part of form design is creating consistent, effective menus. This means following some straightforward design guidelines and organizing your menus consistently and concisely. Here are a few guidelines and suggestions that enable you to make professional looking menus that meet the users' expectations:
Follow Standard Windows Menu Conventions Windows has been around for a long enough period of time that its users have developed certain expectations about how Windows applications should work and look. One of the areas where user expectations are fairly specific is the layout of the menu bar. Take a look at Figure 19.6. In this example, the designer of this menu has chosen to breach the standard Windows menu bar layout convention. Users expect that the menu bar item File comes first, followed by Edit. This design changes the menu bar item order to be Edit, followed by File. The unconventional reordering of the menu bar will probably cause the user to experience initial confusion. In this case, reordering the menu really adds no value to the program, so it is better to stick with the de facto Windows convention.
FIG. 19.6
There is no reason to re-order the standard Windows menu bar; it will only
confuse the users.
Group Menu Items Logically and Concisely Figure 19.7 shows another problem with the example menus. Notice that the illustrated Settings menu has only two submenus, Show Settings and Always on Top. These two submenus should be moved to the File menu. Doing this condenses the menu bar without affecting the functionality or accessibility of the moved items.
FIG. 19.7
Since there are only two items in the Settings menu, a
better choice would be to move them to the File menu.
Use Separator Bars to Group Related Items in a Drop-Down Menu Separator bars provide a level of grouping within a top-level menu. Take Visual Basic's Edit menu for example--related functions such as Copy and Paste are set apart from other items because they logically go together. The separator bars create a visual break in a long menu, allowing the user to quickly know if he or she is looking at the right area. In our example, after the Show Settings and Always on Top drop-down menu items have been moved to the File menu, they can be grouped together by putting a separator bar before and after the items (see Figure 19.8).
See "Controlling a Program with a Menu Bar," Chapter 5
FIG. 19.8
This menu system has been simplified by grouping similar functions.
Avoid Redundant Menu Entries Although it is always a good idea to offer the user multiple ways of performing the same tasks within your program--for example, selecting Edit, Copy or pressing Ctrl+C to copy selected data to the Clipboard--it is not good practice to have a given functionality appear in more than one place within your program's menu system. Nor is it a good idea to have the same menu caption appear in more than one place in your program and perform two entirely different actions. In Figure 19.9, notice that the caption Settings appears both in the File menu and as a menu item. When you select File, Settings, the Settings dialog box appears. However, when you click the Settings menu bar item, the Settings drop-down menu appears. This is poor practice. Not only will having this caption in two different areas of the program's menu confuse the user, having two different behaviors attached to each caption will absolutely confound him.
FIG. 19.9
In this example, the Settings menu item appears in two
places: in the File drop-down menu and the menu bar. This is
a confusing design choice. Avoid redundant menu items.
Avoid Menu Bar Items Without Drop-Down Menus Avoid the situation in which you have a menu bar item that does not have a drop-down menu of selections. In Figure 19.10, you see the About dialog box that appears when you choose About..., which has no menu items under it. A lone top-level item, or orphan, has the same behavior as a command button or drop-down menu item. If that sort of behavior is what you want, a CommandButton control could be used to achieve the same effect. The better solution, however, is to move the orphan menu bar item to another menu with a similar set of functions. This is the same principle discussed earlier in "Group Menu Items Logically and Concisely."
FIG. 19.10
A menu bar item that doesn't invoke drop-down menus might confuse users.
Use the Ellipsis to Denote Menu Entries that Activate Dialog Boxes When an ellipsis (...) appears next to an item in a drop-down menu, it lets users know that selecting this item does not have any immediate results, but rather brings up a dialog box with more options (as you saw with the About... item in the preceding section). Many people unfamiliar with designing Windows applications frequently forget to use it. Using the ellipsis when the situation warrants adds to the professionalism of your application.
When it comes time for a user to make a decision within your program, it is usually more efficient to provide a set of choices from which to select (see Figure 19.11) than requiring typed input. Providing the user with choices reduces the risk of error due to typing mistakes. It also makes input validation much easier, as well as shows the user the range of possible choices in many cases.
FIG. 19.11
Selecting a typeface from a list of available fonts is easier for the user
than typing in a selection.
See "Working with User Choices," Chapter 9
List Boxes versus Combo Boxes Two useful controls for offering choices to the user are the list box and the combo box. The ListBox control allows the user to view a list of all available choices before, during, and after a selection is made. The ListBox control allows no typed input; the user can select one (or sometimes more) item from the list. This can be a drawback should the user need to input data that the program does not provide. Another drawback of the list box is that it requires a good deal of window space to be useful. A list box that shows only two or three items can appear cramped and awkward.
NOTE: Windows standards dictate that when you use a list box, you let the user select an item in one of two ways: selecting it and pressing a button or double-clicking. An example of this behavior (which uses the ListView control) is a File dialog box.
When window space is at a premium, using the ComboBox control might be a better design choice than a list box. The ComboBox control has three styles:
The drawback of using the Simple Combo style is that, like the ListBox control, it requires a good deal of window space to be effective.
FIG. 19.12
Depending on the style setting of a combo box, typed user input may or may
not be allowed.
TIP: A DropDown List style combo box is a useful control for online report viewing. It allows the user to both select a report parameter (for example, Month-to-Date versus Quarter-to-Date) and, at the same time, shows the currently selected item.
Overusing list boxes and combo boxes can also harm an application's performance. If a list box or combo box lists too many items, the control can increase the form's load time. You can reduce the number of items in a list by finding out what the actual limits are. Does a user need all the states in the United States or only the ten with which the company normally does business?
Option Buttons versus Check Boxes To present a fixed number of choices, use the CheckBox and OptionButton controls. A check box gives the user two choices only: on or off. For example, the Windows Explorer Options dialog box (accessed through the View menu) uses a check box to indicate whether to Display the Full MS-DOS p_ath in the title bar or not (see Figure 20.13). Selecting or deselecting a check box has no effect on any other check boxes on a form. Option buttons present the user with a fixed list of mutually exclusive choices. Option buttons are usually grouped by placing related buttons in a frame. Only one option button in a group can be selected at any time; selecting one button in a group automatically deselects the other buttons in that group. The Background tab in Windows' Display Properties dialog box uses option buttons to set the background wallpaper to the exclusive states of Tile or Center (see Figure 19.14).
FIG. 19.13
A good use of check boxes is shown in the lower section of the Windows Explorer
dialog box, which uses two check boxes to present the user with independent on/off
options.
FIG. 19.14
In this dialog box, option buttons are used within a frame to represent a
choice between two mutually exclusive states, Tile or Center.
Perception is reality. No, I'm not having flashback to the 1960s, I am merely referring to how users' observations can influence their like or dislike of your program, regardless of its actual functionality. Application speed is a prime example. You might have written the fastest Visual Basic code ever, but it matters little if the user thinks it runs slow. Visual Basic programmers tend to get defensive when users complain about speed, because "the users don't know what the program is doing." However, there are a few tricks you can use to make your program seem to run faster.
The key to a program's perceived speed is the fact that when a user clicks on an icon, something needs to happen right away. Users are more willing to wait if they think the computer is working as fast as it can. Booting Windows 95 is a good example; it usually takes quite a long time. However, all the graphics, beeps, and hard drive noise keep you distracted enough to make it an acceptable wait. The techniques discussed in this section give you suggestions for creating "faster" Visual Basic applications.
Load Time If you load all of a program's forms at startup, they all appear quickly when the application needs to show them. Although this slows the application's performance at program startup, overall runtime performance is much faster. Simply load all the forms that belong to an application by using the Load method. This method places the forms in memory, but they are invisible to the user until the Show method is executed. This technique works well for applications with a small number of forms (2-5). For applications with more forms, you might use this technique for similar groupings of forms. For example, an accounting payroll application might load all the forms associated with displaying employee information during an employee data-entry session.
The Sub Main Subroutine The General tab of the Project Properties dialog box (which you display by choosing projectname Properties from the Project menu) allows you to choose a startup form or Sub Main (see Figure 19.15). To take advantage of this setting, you need a module with a subroutine named Main. This frees you from having to keep any startup routines within a form's Load event.
FIG. 19.15
After setting your startup object to Sub Main, you can consolidate your program's
initialization tasks into a single procedure.
The Sub Main subroutine is an excellent place for all the initialization code required at startup time. For example, the Sub Main subroutine might contain code for opening configuration files, checking the application's path, and connecting to a networked database. If your initialization procedures are very long, you might want to display a splash screen during this process.
Splash Screens One way to deal with lengthy program startups is to display a splash screen during load time. A splash screen is a form that displays information about the application and its designer (see Figure 19.16). Many commercial applications, including Microsoft Word, Excel, and Visual Basic itself, display splash screens at program startup. A splash screen with a status bar provides the user with visible proof that something is happening.
FIG. 19.16
This splash screen appears when the application first loads to give the user
something to look at while program initialization takes place.
You can also update information in a splash screen to keep the user informed of the tasks being done in setting up the program. A similar technique can be used during a long process, such as modifying a large number of database records.
Regardless of whether you are a member of a large development team or you are a one-coder shop, your code will have to be maintained by someone. Just because you have spent hours of coding and debugging to get a function working just right does not mean that there won't come a time to improve and enhance it. Even maintaining your own code can be a daunting task if you have not seen it in six months (or, in my case, six hours). However, the task doesn't have to be horrendous. If you take certain precautions and use a little foresight, you can make the time needed to maintain your code reasonable and relatively painless.
The most important thing that you can do toward making your code easy to maintain is to make it readable, not only to yourself but also to others. If another programmer cannot read your code, he or she must waste precious time figuring out exactly what the program does and how. Readable code gives others a quick, intuitive feel for how your program works. Also, readability has a definite impact as to how your code is perceived within the professional community. Depending on how you write code, others who have to follow your work will either curse your name or admire your skill.
Many Visual Basic code statements utilize numeric parameter values to specify how an object should behave. This capability makes writing code easier, but makes reading the code afterwards difficult. The solution is to use global constants that represent these numeric values. Code that uses constants is much easier to read.
To use built-in constants, you no longer have to add a text file to your project as you did with versions of Visual Basic prior to version 4. Visual Basic now includes intrinsic (built-in) constants in the language. By using these intrinsic constants, you make your code more readable to all programmers, even those who have not memorized the constant values. Using constants can also help you, especially if you tend to forget what you have done and why. For example, which of the following code lines is more readily understandable?
MsgBox "This is a warning", 64 MsgBox "This is a warning", vbExclamation
When you read code that uses the intrinsic constants, you do not have to remember what each value means.
Writing commented code is a pain, but reading uncommented code--even code that you wrote just yesterday--can be an even greater pain. Trying to figure out the logic of a code segment can be time-consuming. Taking the time on the front end to put in comments, on the other hand, saves you time in the long run. There's an old saying among programmers, "You can never comment too much!" Imagine trying to read and understand the meaning and use of the code in Listing 19.1 without the comments.
` The following routine searches through all the controls ` on a form and checks each control's TAG property. ` If the tag property is a field name, this routine loads ` the current field's value into that control Sub LoadFormData (WndName As Form, dyn As Dynaset) Dim Cntl%, FieldName$, Result$, N%, i% Screen.MousePointer = vbHOURGLASS `Search through all the controls on the indicated form For Cntl% = 0 To WndName.Controls.Count - 1 FieldName$ = WndName.Controls(Cntl%).Tag If TypeOf WndName.Controls(Cntl%) Is OptionButton Then ` Find the value of this field and store in the appropriate ` option button control % = Abs(dyn(FieldName$)) If WndName.Controls(Cntl%).Caption = "YES" Then WndName.Controls(Cntl%).Value = N% ElseIf WndName.Controls(Cntl%).Caption = "NO" Then WndName.Controls(Cntl%).Value = Abs(N% - 1) End If ElseIf TypeOf WndName.Controls(Cntl%) Is ComboBox Then If dyn(FieldName$) <> Null Then ` Format the current field's value Result$ = dyn.Fields(FieldName$) ` Find the field's value in the current combo box For N% = 0 To (WndName.Controls(Cntl%).ListCount - 1) i% = WndName.Controls(Cntl%).ListIndex + 1 WndName.Controls(Cntl%).ListIndex = i% If Len(WndName.Controls(Cntl%).Text) <> 0 Then Exit For End If ext N% End If ` If the control is a text box ElseIf TypeOf WndName.Controls(Cntl%) Is TextBox Then ` If the current field's value is blank then skip If dyn(FieldName$) <> Null Then ` Store the formatted value in the text box WndName.Controls(Cntl%).Text = dyn.Fields(FieldName$) End If End If Next Cntl% Screen.MousePointer = vbDEFAULT End Sub
Listing 20.1 contains the subroutine LoadFormData. You could reference this subroutine in the Load event of any form. Simply provide the name of the recordset containing the data, position, and the table at the appropriate record; place the names of the fields that you want in the appropriate control's Tag property; and run this routine. In instances where you cannot use Bound controls, this routine works amazingly well. Notice that the use of vbHourGlass and vbDefault makes it clear what the program is doing to MousePointer.
Visual Basic allows you to use up to 255 characters to name a variable, sub, or function; it allows 40 characters for a control name. You can take advantage of this feature by giving your variables, functions, and controls names that reflect their identity, purpose, or position. In addition, as we discussed in Chapter 8, it's a good idea to use a naming convention for your objects and variables that helps you determine their type at a glance.
Listing 19.2 shows an example of using descriptive object naming to make your code more readable.
Private Sub cmdChoices_MouseDown(Index As Integer, Button As Integer, Shift As Integer, X As Single, Y As Single) Dim i% `"The pressed button typeface will be set according to the option, opFontFace `value set `Set the old font (the gf prefix denotes global to form) so it can `reset on MouseUp gfOldFontFace$ = cmdChoices(Index).Font `Adjust for the new font setting If opFontFace(0) = True Then cmdChoices(Index).Font = opFontFace(0).Caption Else cmdChoices(Index).Font = opFontFace(1).Caption End If `Query to option buttons and set the caption case for the button depressed For i% = 0 To 2 Select Case i% Case 0 If optFontCase(i%).Value = True Then cmdChoices(Index).Caption = UCase(cmdChoices(Index).Caption) Case 1 If optFontCase(i%).Value = True Then cmdChoices(Index).Caption = LCase(cmdChoices(Index).Caption) Case 2 If optFontCase(i%).Value = True Then cmdChoices(Index).Caption = gfOldFontCase$(Index) End Select ext i% End Sub
Notice in the example that you do not even need to look at the form to know optFontCase is an option button used to select upper- or lowercase. This would have been a little harder to determine if its default name of Option1 had been kept.
Designing an effective Windows application requires a bit more understanding and planning than just putting controls on a form. Implementing a user-centered software development process helps you design cost-effective, user-friendly applications that work well and are easy to deploy and revise.
An application's appearance is as important as what the application does. A poorly thought-out application interface detracts from the application's usefulness because users focus on the bad interface rather than what it does. Be careful how you organize controls and menus. Also be careful to ensure that your program complies with and responds to the user's expectations.
To find information on related topics, see the following chapters:
© Copyright, Macmillan Computer Publishing. All rights reserved.