Visual basic

Chapter 1
Getting Started with
Visual Basic 2008
I’m assuming that you have installed one of the several versions of Visual Studio 2008. For this
book, I used the Professional Edition of Visual Studio, but just about everything discussed in
this book applies to the Standard Edition as well. Some of the features of the Professional Edition
that are not supported by the Standard Edition concern database tools, which are discussed in
Chapters 21 through 24 of this book.
You may have even already explored the new environment on your own, but this book starts
with an overview of Visual Studio and its basic tools. It doesn’t even require any knowledge of
VB 6, just some familiarity with programming at large. As you already know, Visual Basic 2008
is just one of the languages you can use to build applications with Visual Studio 2008. I happen
to be convinced that it is also the simplest, most convenient language, but this isn’t really the
issue; I’m assuming you have your reasons to code in VB, or else you wouldn’t be reading this
book. What you should keep in mind is that Visual Studio 2008 is an integrated environment for
building, testing, debugging, and deploying a variety of applications: Windows applications, web
applications, classes and custom controls, and even console applications. It provides numerous
tools for automating the development process, visual tools for performing many common design
and programming tasks, and more features than any author would hope to cover.
In this chapter, you’ll learn how to do the following:
? Navigate the integrated development environment of Visual Studio
? Understand the basics of aWindows application
Exploring the IntegratedDevelopment Environment
Visual Basic 2008 is just one of the languages you can use to program your applications. The
language is only one aspect of a Windows application. The visual interface of the application isn’t
tied to a speci?c language, and the same tools you’ll use to develop your application’s interface
will also be used by all programmers, regardless of the language they’ll use to code the application.
To simplify the process of application development, Visual Studio provides an environment
that’s common to all languages, which is known as an integrated development environment (IDE).
The purpose of the IDE is to enable the developer to do as much as possible with visual tools,
before writing code.
The IDE provides tools for designing, executing, and debugging your applications. It will be
a while before you explore all the elements of the IDE, and I will explain the various items as
needed in the course of the book. In this section, you’ll look at the basic components of the IDEPetroutsos c01.tex V2 - 01/28/2008 11:43am Page 2
2 CHAPTER 1 GETTING STARTED WITH VISUAL BASIC 2008
needed to build simple Windows applications. You’ll learn how its tools allow you to quickly
design the user interface of your application, as well as how to program the application.
The IDE is your second desktop, and you’ll be spending most of your productive hours in this
environment.
The Start Page
When you run Visual Studio 2008 for the ?rst time, you will be prompted to select the type of
projects you plan to build with Visual Studio, so that the environment can be optimized for that
speci?c type of development. I’m assuming that you have initially selected the Visual Basic Devel-
opment settings, which will optimize your copy of Visual Studio for building Windows and web
applications with Visual Basic 2008. You can always change these settings, as explained at the end
of this section.
After the initial con?guration, you will see a window similar to the one shown in Figure 1.1. The
Recent Projects pane will be empty, of course, unless you have already created some test projects.
Visual Studio 2008 will detect the settings of a previous installation, so if you’re upgrading from
an earlier version of Visual Studio, the initial screen will not be identical to the one shown in
Figure 1.1.
Figure 1.1
This is what you’ll see
when you start Visual
Studio for the ?rst time.
On the Start Page of Visual Studio, you will see the following panes:
Recent Projects Here you see a list of the projects you opened most recently with Visual
Studio, and you can select the one you want to open again— chances are that you will con-
tinue working on the same project as the last time. Each project’s name is a hyperlink, and you
can open it by clicking its name. At the bottom of the Recent Projects section are two hyper-
links, for opening or creating another project.
MSDN: Visual Studio This section is a browser window that displays an MSDN
(the Microsoft Developer Network, which is the de?nitive resource for all Microsoft tech-
nologies and products) page when the computer is connected to the Internet. In this section,Petroutsos c01.tex V2 - 01/28/2008 11:43am Page 3
EXPLORING THE INTEGRATED DEVELOPMENT ENVIRONMENT 3
you will see news about Visual Studio, the supported languages, articles, and other inter-
esting bits of information.
Getting Started This section contains links to basic programming tasks in the product’s
documentation.
Visual Studio Headlines This section contains links to announcements and other news
of interest to VB developers.
Most developers will skip the Start Page. To do so, open the Tools menu and choose the
Import And Export Settings command to start a con?guration wizard. In the ?rst dialog box of
the wizard, select the Reset All Settings check box and click the Next button. The next screen
of the wizard prompts you for the location where the new settings will be saved, so that Visual
Studio can read them every time it starts. Leave the default location as is and click Next again to
see the last screen of the wizard, in which you’re prompted to select a default collection of settings.
This collection depends on the options you’ve installed on your system. I installed Visual
Studio 2008 with Visual Basic only on my system, and I was offered the following options: General
Development Settings, Visual Basic Development Settings, and Web Development Settings.
For the default con?guration of my copy of Visual Studio, and for the purposes of this book, I
chose the Visual Basic Development Settings, so that Visual Studio could optimize the environ-
ment for a typical VB developer. Click the Finish button to see a summary of the process and then
close the wizard.
Starting a New Project
At this point, you can create a new project and start working with Visual Studio. To best explain
the various items of the IDE, we will build a simple form. The form is the window of your
application — it’s what users will see on their Desktop when they run your application.
Open the File menu and choose New Project, or click Create Project/Solution in the Start Page.
In the New Project dialog box that pops up (see Figure 1.2), you’ll see a list of project types you can
create with Visual Studio. The most important ones are Windows Forms Applications, which are
typical Windows applications with one or more forms (windows); Console Applications, which
are simple applications that interact with the user through a text window (the console); Windows
Forms Control Libraries, which are collections of custom controls; and Class Libraries, which are
collections of classes. These are the project types we’ll cover in depth in this book.
If you have installed Visual Basic 2008 Express Edition, you will see fewer project types in the
New Project dialog box, but the projects discussed in this book are included.
Notice the Create Directory For Solution check box in the dialog box of Figure 1.2. By default,
Visual Studio creates a new folder for the project under the folder you have speci?ed in the Loca-
tion box. If youwant to put together a short application to test a feature of the language, or perform
some trivial task, you may not wish to save the project. In this case, just clear the check box to skip
the creation of a new project folder.
You can always save a project at any time by choosing the Save All command from the File
menu. You’ll be prompted at that point about the project’s folder, and Visual Studio will save
the project under the folder you speci?ed. If you decide to discard the project, you can create
a new project or close Visual Studio. Visual Studio will prompt you about an open project that
hasn’t been saved yet, and you can choose not to save it.
You may discover at some point that you have created too many projects, which you don’t
really need. You can remove these projects from your system by deleting the corresponding
folders — no special action is required. You’ll know it’s time to remove the unneeded project
folder when Visual Studio suggests project names such as WindowsApplication9 or Windows-
Application49.Petroutsos c01.tex V2 - 01/28/2008 11:43am Page 4
4 CHAPTER 1 GETTING STARTED WITH VISUAL BASIC 2008
Figure 1.2
The New Project dialog
box
For our project, select the Windows Forms Application template; Visual Studio suggests
the name WindowsApplication1 as the project name. Change it to MyTestApplication, select the
Create Directory For Solution check box, and then click the OK button to create the new project.
What you see now is the Visual Studio IDE displaying the Form Designer for a new project, as
shown in Figure 1.3. The main window of your copy of Visual Studio may be slightly different,
but don’t worry about it. I’ll go through all the components you need to access in the process of
designing, coding, and testing a Windows application.
Figure 1.3
The integrated develop-
ment environment of
Visual Studio 2008 for a
new projectPetroutsos c01.tex V2 - 01/28/2008 11:43am Page 5
EXPLORING THE INTEGRATED DEVELOPMENT ENVIRONMENT 5
The new project contains a form already: the Form1 component in the Solution Explorer. The
main window of the IDE is the Form Designer, and the gray surface on it is the window of your
new application in design mode. Using the Form Designer, you’ll be able to design the visible
interface of the application (place various components of the Windows interface on the form and
set their properties) and then program the application.
The default environment is rather crowded, so let’s hide a few of the toolbars that we won’t use
in the projects of the ?rst few chapters. You can always show any of the toolbars at any time. Open
the View menu and choose Toolbars. You’ll see a submenu with 28 commands that are toggles.
Each command corresponds to a toolbar, and you can turn the corresponding toolbar on or off by
clicking one of the commands in the Toolbars submenu. For now, turn off all the toolbars except
for the Layout and Standard toolbars. These are the toolbars shown by default and you shouldn’t
hide them; if you do, this is the place to make them visible again.
The last item in the Toolbars submenu is the Customize command, which leads to a dialog box
in which you can specify which of the toolbars and which of the commands you want to see. After
you have established a work pattern, use this menu to customize the environment for the way you
want to work with Visual Studio. You can hide just about any component of the IDE, except for
the main menu — after all, you have to be able to undo the changes!
Using the Windows Form Designer
To design the form, youmust place on it all the controls you want to display to the user at runtime.
The controls are the components of the Windows interface (buttons, text boxes, radio buttons,
lists, and so on). Open the Toolbox by moving the pointer over the Toolbox tab at the far left; the
Toolbox, shown in Figure 1.4, pulls out. This Toolbox contains an icon for each control you can
use on your form.
The controls are organized into groups according to each control’s function on the interface.
In the ?rst part of the book, we’ll create simple Windows applications and we’ll use the controls
on the Common Controls tab. When you develop web applications, you will see a different set of
icons in the Toolbox.
To place a control on the form, you can double-click the icon of the control. A new instance
with a default size will be placed on the form. Then you can position and resize it with the mouse.
Or you can select the control from the Toolbox with the mouse and then click and drag the
mouse over the form and draw the outline of the control. A new instance of the control will be
placed on the form, and it will ?ll the rectangle you speci?ed with the mouse. Start by placing a
TextBox control on the form.
The control’s properties will be displayed in the Properties window (see Figure 1.5). This win-
dow, at the far right edge of the IDE and below the Solution Explorer, displays the properties of
the selected control on the form. If the Properties window is not visible, open the View menu and
choose PropertiesWindow, or press F4. If no control is selected, the properties of the selected item
in the Solution Explorer are displayed.
In the Properties window, also known as the Properties Browser, you see the properties that
determine the appearance of the control and (in some cases) its function. The properties are
organized in categories according to their role. The properties that determine the appearance
of the control are listed alphabetically under the header Appearance, the properties that determine
the control’s behavior are listed alphabetically under the header Behavior, and so on. You can
click the AZ button on the window’s title bar to display all properties in alphabetical order.
After you familiarize yourself with the basic properties, you will most likely switch to the
alphabetical list.Petroutsos c01.tex V2 - 01/28/2008 11:43am Page 6
6 CHAPTER 1 GETTING STARTED WITH VISUAL BASIC 2008
Figure 1.4
Windows Forms Toolbox
of the Visual Studio IDE
Rearranging the IDEWindows
As soon as you place a control on the form, the Toolbox retracts to the left edge of the Designer. You
can ?x this window on the screen by clicking the icon with the pin on the Toolbox’s toolbar. (It’s the
icon next to the Close icon at the upper-right corner of the Toolbox window, and it appears only when
the Toolbox window is docked, but not while it’s ?oating.)
You can easily rearrange the various windows that make up the IDE by moving them around with the
mouse. Move the pointer to a window’s title bar, press the left mouse button, and drag the window
around. A window may not follow the mouse, because its position is locked. In this case, click the pin
icon in the upper-right corner of the window to unlock the window’s position and then move it
around with the mouse.
As you move the window, eight semitransparent buttons with arrows appear on the screen, indicat-
ing the area where the window can be docked. Keep moving the window until the pointer hovers overPetroutsos c01.tex V2 - 01/28/2008 11:43am Page 7
EXPLORING THE INTEGRATED DEVELOPMENT ENVIRONMENT 7
one of these buttons, and the docking area appears in semitransparent blue color. Find the desired
docking location for the window and release the mouse. If you release the mouse while the pointer
is not on top of an arrow, the window is not docked. Instead, it remains at the current location as a
?oating window, and you can move it around at will with your mouse.
Most developers would rather work with docked windows, and the default positions of the IDE win-
dows are quite convenient. If you want to open even more windows and arrange them differently on
the screen, use the docking feature of the IDE to dock the additional windows.
Locate the TextBox control’s Text property and set it to My TextBox Control by entering the
string into the box next to the property name. The control’s Text property is the string that appears
in the control (the control’s caption), and most controls have a Text property.
Next locate its BackColor property and select it with the mouse. A button with an arrow
appears next to the current setting of the property. Click this button, and you’ll see a dialog box
withthreetabs(Custom,Web,andSystem),asshowninFigure1.6.Inthisdialogbox,youcan
select the color that will ?ll the control’s background. Set the control’s background color to yellow
and notice that the control’s appearance changes on the form.
One of the settings you’ll want to change is the font of the various controls. While the TextBox
control is still selected on the form, locate the control’s Font property in the Properties window.
You can click the plus sign in front of the property name and set the individual properties of
the font, or you can click the ellipsis button to invoke the Font dialog box. Here you can set the
control’s font and its attributes and then click OK to close the dialog box. Set the TextBox control’s
Font property to Verdana, 14 points, bold. As soon as you close the Font dialog box, the control
on the form is adjusted to the new setting.Petroutsos c01.tex V2 - 01/28/2008 11:43am Page 8
8 CHAPTER 1 GETTING STARTED WITH VISUAL BASIC 2008
Figure 1.5
Properties of a TextBox
control
Figure 1.6
Setting a color prop-
erty in the Properties
windowPetroutsos c01.tex V2 - 01/28/2008 11:43am Page 9
EXPLORING THE INTEGRATED DEVELOPMENT ENVIRONMENT 9
There’s a good chance that the string you assigned to the control’s Text propertywon’t ?t in the
control’s width when rendered in the new font. Select the control on the form with the mouse, and
you will see eight handles along its perimeter. Rest the pointer over any of these handles, and it
will assume a shape indicating the direction in which you can resize the control. Make the control
long enough to ?t the entire string. If you have to, resize the form as well. Click somewhere on the
form, and when the handles along its perimeter appear, resize it with the mouse.
Some controls, such as the Label, Button, and CheckBox controls, support the AutoSize prop-
erty, which determines whether the control is resized automatically to accommodate its caption.
The TextBox control, as well as many others, doesn’t support the AutoSize property. If you
attempt to make the control tall enough to accommodate a few lines of text, you’ll realize that
you can’t change the control’s height. By default, the TextBox control accepts a single line of text,
and you must set its MultiLine property to True to resize the TextBox control vertically.
The Font Is a Design Element
Like documents, forms should be designed carefully and follow the rules of a printed page design. At
the very least, you shouldn’t use multiple fonts on your forms, just as you shouldn’t mix different
fonts on a printed page. You could use two font families on rare occasions, but you shouldn’t overload
your form. You also shouldn’t use the bold style in excess.
To avoid adjusting the Font property of multiple controls on the form, you should set the form’s font
?rst, because each control you place on a form inherits the form’s font. If you change the form’s font,
the controls will be adjusted accordingly, but this may throw off the alignment of the controls on the
form. You should experiment with a few Label controls, select a font that you like that’s appropriate
for your interface (you shouldn’t use a handwritten style with a business application, for example)
and then set the form’s Font property to the desired font. Every time you add a new formto the appli-
cation, you should start by setting its Font property to the same font, so that the entire application
will have a consistent look.
The font is the most basic design element, whether you’re designing forms or a document. Various
components of the form may have a different font size, even a different style (like bold or italics),
but there must be a dominant font family that determines the look of the form. The Verdana fam-
ily was designed for viewing documents on computer monitors and is a popular choice. Another great
choice is Segoe UI, a new font family introduced with Windows Vista. The Segoe Print font has a
distinguished handwritten style, and you can use it with graphics applications.
The second most important design element is color, but you shouldn’t get too creative with colors
unless you’re a designer. I recommend that you stay with the default colors and use similar shades
to differentiate a few elements of the interface.
The design of a modern interface has become a new discipline in application development, and there
are tools for designing interfaces. One of themisMicrosoft’s Expression Studio, which enables design-
ers to design the interface and developers to write code, without breaking each other’s work. You can
download a trial version of Expression Studio from www.microsoft.com/expression.
So far, you’ve manipulated properties that determine the appearance of the control. Now you’ll
change a property that determines not only the appearance, but also the function of the control.
Locate the Multiline property. Its current setting is False. Expand the list of available settingsPetroutsos c01.tex V2 - 01/28/2008 11:43am Page 10
10 CHAPTER 1 GETTING STARTED WITH VISUAL BASIC 2008
and change it to True. (You can also change it by double-clicking the name of the property. This
action toggles the True/False settings.) Switch to the form, select the TextBox control, and make it
as tall as you wish.
The Multiline property determines whether the TextBox control can accept one (if Multiline
=False)ormore(if Multiline = True) lines of text. Set this property to True, go back to the Text
property, set it to a long string, and press Enter. The control breaks the long text intomultiple lines.
If you resize the control, the lines will change, but the entire string will ?t in the control because the
control’s WordWrap property is True. Set it to False to see how the string will be rendered on
the control.
Multiline TextBox controls usually have a vertical scroll bar so users can quickly locate the
section of text that they’re interested in. Locate the control’s ScrollBars property and expand
the list of possible settings by clicking the button with the arrow. This property’s settings are
None, Vertical, Horizontal,and Both.Setitto Vertical,assignaverylongstringtoits Text
property, and watch how the control handles the text. At design time, you can’t scroll the text on
the control; if you attempt to move the scroll bar, the entire control will be scrolled. The scroll bar
will work as expected at runtime (it will scroll the text vertically).
You can also make the control ?ll the entire form. Start by deleting all other controls you may
have placed on the form and then select the multiline TextBox. Locate the Dock property in the
Properties window and keep double-clicking the name of the property until its setting changes
to Fill. (You’ll learn a lot more about docking controls in Chapter 7, ‘‘Working with Forms.’’)
The TextBox control ?lls the form and is resized as you resize the form, both at design time and
runtime.
To examine the control’s behavior at runtime, press F5. The application will be compiled, and
a few moments later, a window ?lled with a TextBox control will appear on the Desktop (like the
one shown in Figure 1.7). This is what the users of your application would see (if this were an
application worth distributing, of course).
Figure 1.7
ATextBoxcontrol
displaying multiple
text lines
Enter some text on the control, select part of the text, and copy it to the Clipboard by pressing
Ctrl+C. You can also copy text from any other Windows application and paste it on the TextBox
control. Right-click the text on the control and you will see the same context menu you get withPetroutsos c01.tex V2 - 01/28/2008 11:43am Page 11
CREATING YOUR FIRST VB APPLICATION 11
Notepad; you can even change the reading order of the text— not that you’d want to do that with
a Western language. When you’re ?nished, open the Debug menu and choose Stop Debugging.
This will terminate your application’s execution, and you’ll be returned to the IDE. The Stop
Debugging command is also available as a button with a blue square icon on the toolbar. Finally,
you can stop the running application by clicking the Close button in the application’s window.
The design of a new application starts with the design of the application’s form, which is the
application’s user interface, or UI. The design of the form determines to a large extent the func-
tionality of the application. In effect, the controls on the form determine how the application will
interact with the user. The form itself is a prototype, and you can demonstrate it to a customer
before even adding a single line of code. By placing controls on the form and setting their proper-
ties, you’re implementing a lot of functionality before coding the application. The TextBox control
with the settings discussed in this section is a functional text editor.
Creating Your FirstVBApplication
In this section, we’ll develop a simple application to demonstrate not only the design of the inter-
face, but also the code behind the interface.We’ll build an application that allows the user to enter
the name of his favorite programming language, and the application will evaluate the choice.
Objectively, VB is a step ahead of all other languages, and it will receive the best evaluation. All
other languages get the same grade — good — but not VB.
The project is called WindowsApplication1. You can download the project from the book’s
website and examine it, but I suggest you follow the steps outlined in this section to build the
project from scratch. Start a new project and use the default name, WindowsApplication1,and
place a TextBox and a Button control on the form. Use themouse to position and resize the controls
on the form, as shown in Figure 1.8.
Figure 1.8
A simple applica-
tion that processes a
user-supplied string
Start by setting the form’s Font property to Segoe UI, 9 pt. Arrange and size the controls as
shown in Figure 1.8. Then place a Label control on the form and set its Text property to Enter
your favorite programming language. The Label will be resized according to its caption, becausePetroutsos c01.tex V2 - 01/28/2008 11:43am Page 12
12 CHAPTER 1 GETTING STARTED WITH VISUAL BASIC 2008
the control’s AutoSize property is True. As you move the controls around on the form, you’ll see
some blue lines connecting the edges of the controls when they’re aligned. These lines are called
snap lines, and they allow you to align controls on the form.
Now youmust insert some code to evaluate the user’s favorite language.Windows applications
are made up of small code segments, called event handlers, which react to speci?c actions such as
the click of a button, the selection of a menu command, the click of a check box, and so on. In the
case of our example, we want to program the action of clicking the button. When the user clicks
the button, we want to execute some code that will display a message.
To insert some code behind the Button control, double-click the control. You’ll see the code
window of the application, which is shown in Figure 1.9. You will see only the de?nition of
the procedure, not the code that is shown between the two statements in the ?gure. The line
Private ... is too long to ?t on the printed page, so I inserted a line continuation character (an
underscore) to break it into two lines. When a line is too long, you can break it into two (or more)
lines by inserting this character. Alternatively, you can turn on theWordWrap feature of the editor
(you’ll see shortly how to adjust the editor’s properties). Notice that I also inserted quite a bit of
space before the second half of the ?rst code line. It’s customary to indent continued lines so they
can be easily distinguished from the other lines. If you enter the line continuation character in the
editor, the following line will be indented automatically.
Figure 1.9
Outline of a subrou-
tine that handles the
Click event of a Button
control
The editor opens a subroutine, which is delimited by the following statements:
Private Sub Button1 Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles Button1.Click
End Sub
At the top of the main pane of the Designer, you will see two tabs named after the form: the
Form1.vb [Design] tab and the Form1.vb tab. The ?rst tab is the Windows Form Designer (in
which you build the interface of the application with visual tools), and the second is the code
editor (in which you insert the code behind the interface). At the top of the code editor, which is
what you see in Figure 1.9, are two ComboBoxes. The one on the left contains the names of the
controls on the form. The one on the right contains the names of events each control recognizes.
When you select a control (or an object, in general) in the left list, the other list’s contents are
adjusted accordingly. To program a speci?c event of a speci?c control, select the name of thePetroutsos c01.tex V2 - 01/28/2008 11:43am Page 13
CREATING YOUR FIRST VB APPLICATION 13
control in the left list (the Objects list) and the name of the event in the right list (the Events list).
While Button1 is selected in the Objects list, open the Events list to see the events to which the
button can react.
The Click event happens to be the default event of the Button control, so when you double-click
a Button on the form, you’re taken to the Button1 Click subroutine. This subroutine is an event
handler, which is invoked automatically every time an event takes place. The event of interest in
our example is the Click event of the Button1 control. Every time the Button1 control on the form
is clicked, the Button1 Click subroutine is activated. To react to the Click event of the button,
you must insert the appropriate code in this subroutine.
There are more than two dozen events for the Button control, and it is among the simpler
controls (after all, what can you do to a button besides clicking it?). Most of the controls recognize
a very large number of events.
The de?nition of the event handler can’t be modi?ed; this is the event handler’s signature (the
arguments it passes to the application). All event handlers in VB 2008 pass two arguments to
the application: the sender argument, which is an object that represents the control that ?red the
event, and the e argument, which provides additional information about the event.
The name of the subroutine is made up of the name of the control, followed by an underscore
and the name of the event. This is just the default name, and you can change it to anything you like
(such as EvaluateLanguage, for this example, or StartCalculations). What makes this subrou-
tine an event handler is the keyword Handles at the end of the statement. The Handles keyword
tells the compiler which event this subroutine is supposed to handle. Button1.Click is the Click
event of the Button1 control. If there were another button on the form, the Button2 control, you’d
have to write code for a subroutine that would handle the Button2.Click event. Each control
recognizes many events, and you can provide a different event handler for each control and event
combination. Of course, we never program every possible event for every control.
The controls have a default behavior and handle the basic events on their own. The TextBox
control knows how to handle keystrokes. The CheckBox control (a small square with a check
mark) changes state by hiding or displaying the check mark every time it’s clicked. The ScrollBar
control moves its indicator (the button in the middle of the control) every time you click one of the
arrows at the two ends. Because of this default behavior of the controls, you need not supply any
code for the events of most controls on the form.
If you change the name of the control after you have inserted some code in an event handler, the
name of the event handled by the subroutine will be automatically changed. The name of the sub-
routine, however, won’t change. If you change the name of the Button1 control to bttnEvaluate,
the subroutine’s header will become
Private Sub Button1 Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles bttnEvaluate.Click
End Sub
Rename the Button1 Click subroutine to EvaluateLanguage. You must edit the code to
change the name of the event handler. I try to name the controls before adding any code to the
application, so that their event handlers will be named correctly. Alternatively, you can use your
own name for each event handler. The default names of the controls you place on a form are quite
generic, and you should change them to something more meaningful. I usually pre?x the con-
trol names with a few characters that indicate the control’s type (such as txt, lbl, bttn,andso
on), followed by a meaningful name. Names such as txtLanguage and bttnEvaluate make yourPetroutsos c01.tex V2 - 01/28/2008 11:43am Page 14
14 CHAPTER 1 GETTING STARTED WITH VISUAL BASIC 2008
code far more readable. It’s a good practice to change the default names of the controls as soon
as you add the controls to the form. Names such as Button1, Button2, Button3, and so on, don’t
promote the readability of your code. With the exception of this ?rst sample project, I’m using
more-meaningful names for the controls used in this book’s projects.
Let’s add some code to the Click event handler of the Button1 control. When this button is
clicked, we want to examine the text in the text box. If it’s Visual Basic,wedisplayamessage;if
not, we display a different message. Insert the lines of Listing 1.1 between the Private Sub and
End Sub statements. (I’m showing the entire listing here; there’s no reason to retype the ?rst and
last statements.)
Listing 1.1: Processing a User-Supplied String
Private Sub EvaluateLanguage(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles Button1.Click
Dim language As String
language = TextBox1.Text
If language = ”Visual Basic” Then
MsgBox(”We have a winner!”)
Else
MsgBox(language & ”is not a bad language.”)
End If
End Sub
Here’s what this code does. First, it assigns the text of the TextBox control to the variable lan-
guage.A variable is a named location in memory where a value is stored. Variables are where we
store the intermediate results of our calculations when we write code. All variables are declared
with a Dim statement and have a name and a type.
You could also declare and assign a value to the language variable in a single step:
Dim language = TextBox1.Text
The compiler will create a String variable, because the statement assigns a string to the variable.
We’ll come back to the topic of declaring and initializing variables in Chapter 2, ‘‘Variables and
Data Types.’’
Then the program compares the value of the language variable to the literal Visual Basic,and
depending on the outcome of the comparison, it displays one of two messages. The MsgBox()
function displays the speci?ed message in a small window with the OK button, as shown in
Figure 1.8. Users can view the message and then click the OK button to close the message box.
Even if you’re not familiar with the syntax of the language, you should be able to understand
what this code does. Visual Basic is the simplest of the languages supported by Visual Studio 2008,
and we will discuss the various aspects of the language in detail in the following chapters. In the
meantime, you should try to understand the process of developing a Windows application: how
to build the visible interface of the application and how to program the events to which you want
your application to react.
The code of our ?rst application isn’t very robust. If the user doesn’t enter the string with the
exact spelling shown in the listing, the comparison will fail.We can convert the string to uppercasePetroutsos c01.tex V2 - 01/28/2008 11:43am Page 15
CREATING YOUR FIRST VB APPLICATION 15
and then compare it with VISUAL BASIC to eliminate differences in case. To convert a string to
uppercase, use the ToUpper method of the String class. The following expression returns the string
stored in the language variable, converted to uppercase:
language.ToUpper
We should also take into consideration the fact that the user may enter VB or VB 2008,andso
on. In the following section, we’ll further improve our application. You never know what users
may throw at your application, so whenever possible you should try to limit their responses to the
number of available choices. In our case, we can display the names of certain languages (the ones
we’re interested in) and force the user to select one of them.
One way to display a limited number of choices is to use a ComboBox control. In the following
section, we’ll revise our sample application so that users won’t have to enter the name of the
language. We’ll force them to select their favorite language from a list so that we won’t have to
validate the string supplied by the user.
Making the Application More User-Friendly
Start a new project: theWindowsApplication2 project. Do not select the Create Directory For Solu-
tion check box; we’ll save the project from within the IDE. As soon as the project is created, open
the File menu and choose Save All to save the project. When the Save Project dialog box appears,
click the Browse button to select the folder where the project will be saved. In the Project Location
dialog box that appears, select an existing folder or create a new folder such as MyProjects or
VB.NET Samples.
Open the Toolbox and double-click the icon of the ComboBox tool. A ComboBox control will
be placed on your form. Now place a Button control on the form and position it so that your
form looks like the one shown in Figure 1.10. Then set the button’s Text property to Evaluate
My Choice.
Figure 1.10
Displaying options in a
ComboBox control
We must now populate the ComboBox control with the valid choices. Select the ComboBox
control on the form by clicking it with the mouse and locate its Items property in the Properties
window. The setting of this property is Collection, which means that the Items property doesn’t
have a single value; it’s a collection of items (strings, in this case). Click the ellipsis button and
you’ll see the String Collection Editor dialog box, as shown in Figure 1.11.Petroutsos c01.tex V2 - 01/28/2008 11:43am Page 16
16 CHAPTER 1 GETTING STARTED WITH VISUAL BASIC 2008
Figure 1.11
Click the ellipsis button
next to the Items prop-
erty of a ComboBox to
see the String Collection
Editor dialog box.
The main pane in the String Collection Editor dialog box is a TextBox, in which you can enter
the items you want to appear in the ComboBox control at runtime. Enter the following strings, one
per row and in the order shown here:
C++
C#
Visual Basic
Java
Cobol
Click the OK button to close the dialog box. The items will not appear on the control at design
time, but you will see them when you run the project. Before running the project, set one more
property. Locate the ComboBox control’s Text property and set it to Select your favorite pro-
gramming language. This is not an item of the list; it’s the string that will initially appear on the
control.
You can run the project now and see how the ComboBox control behaves. Press F5 and wait
a few seconds. The project will be compiled, and you’ll see its form on your Desktop, on top of
the Visual Studio window. I’m sure you know how the ComboBox control behaves in a typical
Windows application, and our sample application is no exception. You can select an item on the
control, either with the mouse or with the keyboard. Click the button with the arrow to expand the
list and then select an item with the mouse. Or press the down or up arrow keys to scroll through
the list of items. The control isn’t expanded, but each time you click an arrow button, the next or
previous item in the list appears on the control. Press the Tab key to move the focus to the Button
control and press the spacebar to emulate a Click event (or simply click the Button control).
We haven’t told the application what to do when the button is clicked, so let’s go back and
add some code to the project. Stop the application by clicking the Stop button on the toolbar (the
solid black square) or by choosing Debug  Stop Debugging from the main menu.When the form
appears in design mode, double-click the button, and the code window will open, displaying an
empty Click event handler. Insert the statements shown in Listing 1.2 between the Private Sub
and End Sub statements.Petroutsos c01.tex V2 - 01/28/2008 11:43am Page 17
CREATING YOUR FIRST VB APPLICATION 17
Listing 1.2: The Revised Click Event Handler
Private Sub Button1 Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles Button1.Click
Dim language As String
language = ComboBox1.Text
If language = ”Visual Basic” Then
MsgBox(”We have a winner!”)
Else
MsgBox(language & ”is not a bad language.”)
End If
End Sub
When the form is ?rst displayed, a string that doesn’t correspond to a language is displayed
in the ComboBox control. We can preselect one of the items from within our code when the form
is ?rst loaded. When a form is loaded, the Load event of the Form object is raised. Double-click
somewhere on the form and the editor will open the form’s Load event handler:
Private Sub Form1 Load(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles MyBase.Load
End Sub
Enter the following code to select the item Visual Basic when the form is loaded:
Private Sub Form1 Load(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles MyBase.Load
ComboBox1.SelectedIndex = 2
End Sub
SelectedIndex is a property of the ComboBox control that determines the selected item. You
can set it to an integer value from within your code to select an item on the control, and you can
also use it to retrieve the index of the selected item in the list. Instead of comparing strings, we
can compare the SelectedIndex property to the value that corresponds to the index of the item
Visual Basic, with a statement such as the following:
If ComboBox1.SelectedIndex = 2 Then
MsgBox(”We have a winner!”)
Else
MsgBox(ComboBox1.Text & ”is not a bad language.”)
End If
The Text property of the ComboBox control returns the text on the control, and we use it to
print the selected language’s name. Of course, if you insert or remove items from the list, you
must edit the code accordingly. If you run the application and test it thoroughly, you’ll realizePetroutsos c01.tex V2 - 01/28/2008 11:43am Page 18
18 CHAPTER 1 GETTING STARTED WITH VISUAL BASIC 2008
that there’s a problem with the ComboBox control. Users can type a new string in the control,
which will be interpreted as a language. By default, the ComboBox control allows users to type in
something, in addition to selecting an item from the list. To change the control’s behavior, select
it on the form and locate its DisplayStyle property in the Properties window. Expand the list of
possible settings for the control and change the property’s value from DropDown to DropDown-
List. Run the application again and test it; our sample application has become bulletproof. It’s a
simple application, but you’ll see more techniques for building robust applications in Chapter 4,
‘‘GUI Design and Event-Driven Programming.’’
The controls on the Toolbox are more than nice pictures we place on our forms. They encapsu-
late a lot of functionality and expose properties that allow us to adjust their appearance and their
functionality. Most properties are usually set at design time, but quite frequently we change the
properties of various controls from within our code.
Now that you’re somewhat familiar with the process of building Windows applications, and
before you look into any additional examples, I will quickly present the components of the Visual
Studio IDE.
Understanding the IDE Components
The IDE of Visual Studio 2008 contains numerous components, and it will take you a while to
explore them. It’s practically impossible to explain in a single chapter what each tool, window, and
menu command does. We’ll discuss speci?c tools as we go along and as the topics get more
and more advanced. In this section, I will go through the basic items of the IDE — the ones we’ll
use in the following few chapters to build simple Windows applications.
The IDE Menu
The IDE menu provides the following commands, which lead to submenus. Notice that most
menus can also be displayed as toolbars. Also, not all options are available at all times. The options
that cannot possibly apply to the current state of the IDE are either invisible or disabled. The Edit
menu is a typical example. It’s quite short when you’re designing the formand quite lengthy when
you edit code. The Data menu disappears altogether when you switch to the code editor — you
can’t use the options of this menu while editing code. If you open an XML document in the IDE,
the XML command will be added to the main menu of Visual Studio.
File Menu
The File menu contains commands for opening and saving projects or project items, as well as
commands for adding new or existing items to the current project. For the time being, use the
New  Project command to create a new project, Open  Project/Solution to open an existing
project or solution, Save All to save all components of the current project, and the Recent Projects
submenu to open one of the recent projects.
Edit Menu
The Edit menu contains the usual editing commands. Among these commands are the Advanced
command and the IntelliSense command. Both commands lead to submenus, which are discussed
next. Note that these two items are visible only when you’re editing your code, and are invisible
while you’re designing a form.Petroutsos c01.tex V2 - 01/28/2008 11:43am Page 19
UNDERSTANDING THE IDE COMPONENTS 19
Edit  Advanced Submenu
The more-interesting options of the Edit  Advanced submenu are the following:
View White Space Space characters (necessary to indent lines of code and make it easy to
read) are replaced by periods.
Word Wrap When a code line’s length exceeds the length of the code window, the line is
automatically wrapped.
Comment Selection/Uncomment Selection Comments are lines you insert between your
code’s statements to document your application. Every line that begins with a single quote
is a comment; it is part of the code, but the compiler ignores it. Sometimes, we want to dis-
ableafewlinesfromourcodebutnotdeletethem(becausewewanttobeabletorestore
them later). A simple technique to disable a line of code is to comment it out (insert the com-
ment symbol in front of the line). This command allows you to comment (or uncomment)
largesegmentsofcodeinasinglemove.
Edit  IntelliSense Submenu
The Edit  IntelliSense menu item leads to a submenu with ?ve options, which are described
next. IntelliSense is a feature of the editor (and of other Microsoft applications) that displays as
much information as possible, whenever possible. When you type the name of a control and the
following period, IntelliSense displays a list of the control’s properties and methods, so that you
can select the desired one, rather than guessing its name. When you type the name of a function
and the opening parenthesis, IntelliSense will display the syntax of the function — its arguments.
The IntelliSense submenu includes the following options:
List Members When this option is on, the editor lists all the members (properties, methods,
events, and argument list) in a drop-down list. This list will appear when you enter the name of
an object or control followed by a period. Then you can select the desired member from the list
with the mouse or with the keyboard. Let’s say your form contains a control named TextBox1
and you’re writing code for this form. When you enter the name of the control followed by
aperiod(TextBox1.), a list with the members of the TextBox control will appear (as seen in
Figure 1.12).
In addition, a description of the selected member is displayed in a ToolTip box, as you can
see in the same ?gure. Select the Text property and then enter the equal sign, followed by a
string in quotes, as follows:
TextBox1.Text = ”Your User Name”
If you select a property that can accept a limited number of settings, you will see the names
of the appropriate constants in a drop-down list. If you enter the following statement, you will
see the constants you can assign to the property (see Figure 1.13):
TextBox1.TextAlign =
Again, you can select the desired value with the mouse. The drop-down list with the members
of a control or object (the Members list) remains open until you type a terminator key (the Esc
or End key) or select a member by pressing the space bar or the Enter key.Petroutsos c01.tex V2 - 01/28/2008 11:43am Page 20
20 CHAPTER 1 GETTING STARTED WITH VISUAL BASIC 2008
Figure 1.12
Viewing the members
of a control in the
IntelliSense
drop-down list
Figure 1.13
Viewing the possible
settings of a prop-
erty in the IntelliSense
drop-down listPetroutsos c01.tex V2 - 01/28/2008 11:43am Page 21
UNDERSTANDING THE IDE COMPONENTS 21
Parameter Info While editing code, you can move the pointer over a variable, method, or
property and see its declaration in a yellow pop-up box. You can also jump to the variable’s
de?nition or the body of a procedure by choosing Go To De?nition from the context menu that
will appear if you right-click the variable or method name in the code window.
Quick Info This is another IntelliSense feature that displays information about commands
and functions. When you type the opening parenthesis following the name of a function, for
example, the function’s arguments will be displayed in a ToolTip box (a yellow horizontal box).
The ?rst argument appears in bold font; after entering a value for this argument, the next one is
shown in bold. If an argument accepts a ?xed number of settings, these values will appear in a
drop-down list, as explained previously.
Complete Word The Complete Word feature enables you to complete the current word by
pressing Ctrl+spacebar. For example, if you type TextB and then press Ctrl+spacebar, you
will see a list of words that you’re most likely to type (TextBox, TextBox1, and so on).
Insert Snippet This command opens the Insert Snippet window at the current location in the
code editor window. Code snippets, which are an interesting feature of Visual Studio 2008, are
discussed in the section ‘‘Using Code Snippets’’ later in this chapter.
Edit  Outlining Submenu
A practical application contains a substantial amount of code in a large number of event han-
dlers and custom procedures (subroutines and functions). To simplify the management of the
code window, the Outlining submenu contains commands that collapse and expand the various
procedures.
Let’s say you’re ?nished editing the Click event handlers of several buttons on the form. You
can reduce these event handlers to a single line that shows the names of the procedures and a
plus sign in front of them. You can expand a procedure’s listing at any time by clicking the plus
sign in front of its name. When you do so, a minus sign appears in front of the procedure’s name,
and you can click it to collapse the body of the procedure again. The Outlining submenu contains
commands to handle the outlining of the various procedures, or turn off outlining and view the
complete listings of all procedures. You will use these commands as you write applications with
substantial amounts of code:
Toggle Outlining Expansion This option lets you change the outline mode of the current
procedure. If the procedure’s de?nition is collapsed, the code is expanded, and vice versa.
Toggle All Outlining This option is similar to the Toggle Outlining Expansion option, but
it toggles the outline mode of the current document. A form is reduced to a single statement.
A ?le with multiple classes is reduced to one line per class.
Stop Outlining This option turns off outlining and adds a new command to the
Outlining submenu, Start Automatic Outlining, which you can select to turn on automatic
outlining again.
Collapse To De?nitions This option reduces the listing to a list of procedure headers.
View Menu
This menu contains commands to display any toolbar or window of the IDE. You have already
seen the Toolbars menu (in the ‘‘Starting a New Project’’ section). The Other Windows command
leads to a submenu with the names of some standard windows, including the Output and Com-
mand windows. The Output window is the console of the application. The compiler’s messages,Petroutsos c01.tex V2 - 01/28/2008 11:43am Page 22
22 CHAPTER 1 GETTING STARTED WITH VISUAL BASIC 2008
for example, are displayed in the Output window. The Command window allows you to enter
and execute statements.When you debug an application, you can stop it and enter VB statements
in the Command window.
Project Menu
Thismenu contains commands for adding items to the current project (an itemcan be a form, a ?le,
a component, or even another project). The last option in this menu is the Project Properties com-
mand, which opens the project’s Properties Pages. The Add Reference and Add Web Reference
commands allow you to add references to .NET components and web components, respectively.
Build Menu
The Build menu contains commands for building (compiling) your project. The two basic com-
mands in this menu are Build and Rebuild All. The Build command compiles (builds the exe-
cutable) of the entire solution, but it doesn’t compile any components of the project that haven’t
changed since the last build. The Rebuild All command does the same, but it clears any existing
?les and builds the solution from scratch.
Debug Menu
This menu contains commands to start or end an application,aswellasthebasicdebuggingtools.
The basic commands of this menu are discussed brie?y in Chapter 4 and in Appendix B.
Data Menu
This menu contains commands you will use with projects that access data. You’ll see how to
use this short menu’s commands in the discussion of the visual database tools in Chapters 21 and
22 of the book.
Format Menu
The Format menu, which is visible only while you design a Windows or web form, contains
commands for aligning the controls on the form. The commands of this menu are discussed in
Chapter 4. The Format menu is invisible when you work in the code editor — its commands apply
to the visible elements of the interface.
Tools Menu
This menu contains a list of useful tools, such as the Macros command, which leads to a submenu
with commands for creating macros. Just as you can create macros in a Microsoft Of?ce applica-
tion to simplify many tasks, you can create macros to automate many of the repetitive tasks you
perform in the IDE. The last command in this menu, the Options command, leads to the Options
dialog box, in which you can fully customize the environment. The Choose Toolbox Items com-
mand opens a dialog box that enables you to add more controls to the Toolbox. In Chapter 12,
‘‘Building Custom Windows Controls,’’ you’ll learn how to design custom controls and add them
to the Toolbox.
Window Menu
This is the typical Window menu of any Windows application. In addition to the list of open
windows, it also contains the Hide command, which hides all toolboxes, leaving the entirePetroutsos c01.tex V2 - 01/28/2008 11:43am Page 23
UNDERSTANDING THE IDE COMPONENTS 23
window of the IDE devoted to the code editor or the Form Designer. The toolboxes don’t dis-
appear completely; they’re all retracted, and you can see their tabs on the left and right edges of
the IDE window. To expand a toolbox, just hover the mouse pointer over the corresponding tab.
Help Menu
This menu contains the various help options. The Dynamic Help command opens the Dynamic
Help window, which is populated with topics that apply to the current operation. The Index
command opens the Index window, in which you can enter a topic and get help on the speci?c
topic.
Toolbox Window
The Toolbox window contains all the controls you can use to build your application’s interface.
This window is usually retracted, and you must move the pointer over it to view the Toolbox. The
controls in the Toolbox are organized in various tabs, so take a look at them to become familiar
with the controls and their functions.
In the ?rst few chapters, we’ll work with the controls in the Common Controls and Menus &
Toolbars tabs. The Common Controls tab contains the icons of the most common Windows con-
trols. The Data tab contains the icons of the objects you will use to build data-driven applications
(they’re explored later in this book). The Dialogs tab contains controls for implementing the com-
mon dialog controls, which are so common inWindows interfaces; they’re discussed in Chapter 8,
‘‘MoreWindows Controls.’’
Solution Explorer Window
The Solution Explorer window contains a list of the items in the current solution. A solution can
contain multiple projects, and each project can contain multiple items. The Solution Explorer
displays a hierarchical list of all the components, organized by project. You can right-click any
component of the project and choose Properties in the context menu to see the selected com-
ponent’s properties in the Properties window. If you select a project, you will see the Project
Properties dialog box. You will ?nd more information on project properties in the following
chapter.
If the solution contains multiple projects, you can right-click the project you want to become
the startup form and select Set As StartUp Project. You can also add items to a project with the
Add Item command of the context menu, or remove a component from the project with the
Exclude From Project command. This command removes the selected component from the project,
but doesn’t affect the component’s ?le on the disk. The Delete command removes the selected
component from the project and also deletes the component’s ?le from the disk.
Properties Window
This window (also known as the Properties Browser) displays all the properties of the selected
component and its settings. Every time you place a control on a form, you switch to this window
to adjust the appearance of the control. You have already seen how to manipulate the properties
of a control through the Properties window.
Many properties are set to a single value, such as a number or a string. If the possible settings
of a property are relatively few, they’re displayed as meaningful constants in a drop-down list.
Other properties are set through a more elaborate interface. Color properties, for example, are set
from within a Color dialog box that’s displayed right in the Properties window. Font properties
are set through the usual Font dialog box. Collections are set in a Collection Editor dialog box,Petroutsos c01.tex V2 - 01/28/2008 11:43am Page 24
24 CHAPTER 1 GETTING STARTED WITH VISUAL BASIC 2008
in which you can enter one string for each item of the collection, as you did for the items of the
ComboBox control earlier in this chapter.
If the Properties window is hidden, or if you have closed it, you can either choose View 
Properties Window, or right-click a control on the form and choose Properties. Or you can simply
press F4 to bring up this window. There will be times when a controlmight totally overlap another
control, and you won’t be able to select the hidden control and view its properties. In this case,
you can select the desired control in the ComboBox at the top of the Properties window. This box
contains the names of all the controls on the form, and you can select a control on the form by
selecting its name on this box.
Output Window
The Output window is where many of the tools, including the compiler, send their output. Every
time you start an application, a series of messages is displayed in the Output window. These
messages are generated by the compiler, and you need not understand them at this point. If the
Output window is not visible, choose View  Other Windows  Output from the menu.
Command and Immediate Windows
While testing a program, you can interrupt its execution by inserting a so-called breakpoint.When
the breakpoint is reached, the program’s execution is suspended, and you can execute a statement
in the Immediate window. Any statement that can appear in your VB code can also be executed in
the Immediate window. To evaluate an expression, enter a question mark followed by the expres-
sion you want to evaluate, as in the following samples, where result is a variable in the program
you interrupted:
? Math.Log(35)
? ”The answer is ” & result.ToString
You can also send output to this window from within your code with the Debug.Write and
Debug.WriteLine methods. Actually, this is a widely used debugging technique — to print the
values of certain variables before entering a problematic area of the code. There are more elaborate
tools to help you debug your application, and you’ll ?nd a discussion in Appendix B, but printing
a few values to the Immediate window is a time-honored practice in programming with VB.
In many of the examples of this book, especially in the ?rst few chapters, I use the Debug.
WriteLine statement to print something to the Immediate window. To demonstrate the use of the
DateDiff() function, for example, I’ll use a statement like the following:
Debug.WriteLine(DateDiff(DateInterval.Day, #3/9/2007#, #5/15/2008#))
When this statement is executed, the value 433 will appear in the Immediate window. This
statement demonstrates the syntax of the DateDiff() function, which returns the difference
between the two dates in days. Sending some output to the Immediate window to test a function
or display the results of intermediate calculations is a common practice.
To get an idea of the functionality of the Immediate window, switch back to your ?rst sample
application and insert the Stop statement after the End If statement in the button’s Click event
handler. Run the application, select a language, and click the button on the form. After displaying
a message box, the application will reach the Stop statement and its execution will be suspended.Petroutsos c01.tex V2 - 01/28/2008 11:43am Page 25
SETTING ENVIRONMENT OPTIONS 25
You’ll see the Immediate window at the bottomof the IDE. If it’s not visible, open the Debugmenu
and choose Windows  Immediate. In the Immediate window, enter the following statement:
? ComboBox1.Items.Count
Then press Enter to execute it. Notice that IntelliSense is present while you’re typing in the Imme-
diate window. The expression prints the number of items in the ComboBox control. (Don’t worry
about the numerous properties of the control and the way I present them here; they’re discussed
in detail in Chapter 6, ‘‘Basic Windows Controls.’’) As soon as you press Enter, the value 5 will be
printed on the following line.
You can also manipulate the controls on the form from within the Immediate window. Enter
the following statement and press Enter to execute it:
ComboBox1.SelectedIndex = 4
The ?fth item on the control will be selected (the indexing of the items begins with 0). How-
ever, you can’t see the effects of your changes, because the application isn’t running. Press F5 to
resume the execution of the application and you will see that the item Cobol is now selected in the
ComboBox control.
The Immediate window is available only while the application’s execution is suspended. To
continue experimenting with it, click the button on the form to evaluate your choice. When the
Stop statement is executed again, you’ll be switched to the Immediate window.
Unlike the Immediate window, the Command window is available at design time. The Com-
mand window allows you to access all the commands of Visual Studio by typing their names in
this window. If you enter the string Edit followed by a period, you will see a list of all commands
of the Edit menu, including the ones that are not visible at the time, and you can invoke any of
these commands and pass arguments to them. For example, if you enter Edit.Find ”Margin” in
the Command window and then press Enter, the ?rst instance of the string Margin will be located
in the open code window. To start the application, you can type Debug.Start.Youcanaddanew
project to the current solution with the AddProj command, and so on. Most developers hardly
ever use this window in designing or debugging applications.
Error List Window
This window is populated by the compiler with error messages, if the code can’t be successfully
compiled. You can double-click an error message in this window, and the IDE will take you to the
line with the statement in error — which you should ?x. Change the MsgBox() function name to
MssgBox(). As soon as you leave the line with the error, the name of the function will be under-
lined with a wiggly red line and the following error description will appear in the Error List
window:
Name ’MssgBox’ is not declared
Setting EnvironmentOptions
The Visual Studio IDE is highly customizable. I will not discuss all the customization options here,
but I will show you how to change the default settings of the IDE. Open the Tools menu and select
Options (the last item in the menu). The Options dialog box appears, in which you can set all thePetroutsos c01.tex V2 - 01/28/2008 11:43am Page 26
26 CHAPTER 1 GETTING STARTED WITH VISUAL BASIC 2008
options regarding the environment. Figure 1.14 shows the options for the fonts of the various
items of the IDE. Here you can set the font for the Text Editor, dialog boxes, toolboxes, and so on.
Select an item in the tree in the left pane list and then set the font for this item in the box below.
Figure 1.14
The Fonts And Colors
options
Figure 1.15 shows the Projects And Solutions options. The top box indicates the default location
for new projects. The Save New Projects When Created check box determines whether the editor
will create a new folder for the project when it’s created. If you uncheck this box, then Visual
Studio will create a folder in the Temp folder. Projects in the Temp folder will be removed when
you run the Disk Cleanup utility to claim more space on your hard drives.
Figure 1.15
The Projects And Solu-
tions options
By default, Visual Studio saves the changes to the current project every time you press F5. You
can change this behavior by setting the Before Building option in the Build And Run page, under
the Project And Solutions branch. If you change this setting, you must save your project from time
to time with the File  Save All command.
Most of the tabs in the Options dialog box are straightforward, and you should take a look at
them. If you don’t like some of the default aspects of the IDE, this is the place to change them. IfPetroutsos c01.tex V2 - 01/28/2008 11:43am Page 27
BUILDING A CONSOLE APPLICATION 27
you switch to the Basic item under the Text Editor branch of the tree in the left pane of the Options
dialog box, you will ?nd the Line Numbers option. Select this check box to display numbers
in front of each line in the code window. The Options dialog box contains a lot of options for
customizing your work environment, and it’s worth exploring on your own.
Building a ConsoleApplication
Apart from Windows applications, you can use Visual Studio 2008 to build applications that run
in a command prompt window. The command prompt window isn’t really a DOS window, even
though it looks like one. It’s a text window, and the only way to interact with an application is to
enter lines of text and read the output generated by the application, which is displayed in this text
window, one line at a time. This type of application is called a console application, and I’m going
to demonstrate console applications with a single example. We will not return to this type of
application later in the book because it’s not what you’re supposed to do as aWindows developer.
The console application you’ll build in this section, ConsoleApplication1, prompts the user to
enter the name of her favorite language. It then prints the appropriate message on a new line, as
shown in Figure 1.16.
Figure 1.16
A console application
uses the command
prompt window to inter-
act with the user.
Start a new project. In the New Project dialog box, select the template Console Application. You
can also change its default name from ConsoleApplication1 to a more descriptive name. For this
example, don’t change the application’s name.
A console application doesn’t have a user interface, so the ?rst thing you’ll see is the code
editor’s window with the following statements:
Module Module1
Sub Main()
End Sub
End Module
Unlike a Windows application, which is a class, a console application is a module. Main() is
the name of a subroutine that’s executed automatically when you run a console application. The
code you want to execute must be placed between the statements Sub Main() and End Sub.Insert
the statements shown in Listing 1.3 in the application’s Main() subroutine.Petroutsos c01.tex V2 - 01/28/2008 11:43am Page 28
28 CHAPTER 1 GETTING STARTED WITH VISUAL BASIC 2008
Listing 1.3: Console Application
Module Module1
Sub Main()
Console.WriteLine(”Enter your favorite language”)
Dim language As String
language = Console.ReadLine()
language = language.ToUpper
If language = ”VISUAL BASIC” Or
language = ”VB” Or
language = ”VB.NET” Then
Console.WriteLine(”We have a winner!”)
Else
Console.WriteLine(language & ”is not a bad language.”)
End If
Console.WriteLine()
Console.WriteLine()
Console.WriteLine(”PRESS ENTER TO EXIT”)
Console.ReadLine()
End Sub
End Module
This code is quite similar to the code of the equivalent Windows applications we developed
earlier, except that it uses the Console.WriteLine statement to send its output to the command
prompt window instead of a message box.
A console application doesn’t react to events because it has no visible interface. However, it’s
easy to add some basic elements of the Windows interface to a console application. If you change
the Console.WriteLine method call into the MsgBox() function, the message will be displayed in
a message box.
The reason to build a console application is to test a speci?c feature of the language without
having to build a user interface. Many of the examples in the documentation are console applica-
tions; they demonstrate the topic at hand and nothing more. If you want to test the DateDiff()
function, for example, you can create a new console application and enter the lines of Listing 1.4
in its Main() subroutine.
Listing 1.4: Testing the DateDiff() Function with a Console Application
Sub Main()
Console.WriteLine(DateDiff(DateInterval.Day, #3/9/2000#, #5/15/2008#))
Console.WriteLine(”PRESS ENTER TO EXIT”)
Console.ReadLine()
End Sub
The last two lines will be the same in every console application you write. Without them, the
command prompt window will close as soon as the End Sub statement is reached, and you won’tPetroutsos c01.tex V2 - 01/28/2008 11:43am Page 29
USING CODE SNIPPETS 29
have a chance to see the result. The Console.ReadLine method waits until the user presses the
Enter key.
Console applications are convenient for testing short code segments, but Windows program-
ming is synonymous with designing graphical user interfaces, so you won’t ?nd any more console
applications in this book.
Using Code Snippets
Visual Basic 2008 comes with a lot of prede?ned code snippets for selected actions, and you can
insert these snippets in your code as needed. Let’s say you want to insert the statements for writing
some text to a ?le, but you have no idea how to access ?les. Create an empty line in the listing
(press the Enter key a couple of times at the end of a code line). Then open the Edit menu and
choose IntelliSense  Insert Snippet (or right-click somewhere in the code window and choose
Insert Snippet from the context menu).
You will see on the screen a list of the snippets, organized in folders according to their function,
as shown in Figure 1.17. Select the fundamentals folder, which will display another list of options:
collections and arrays, datatypes, ?lesystem,and math. Double-click the ?lesystem item to see a list of
common ?le-related tasks, as shown in Figure 1.18. Locate the item Write Text To A File in the list
and double-click it to insert the appropriate snippet at the current location in the code window.
Figure 1.17
The code snippets orga-
nized according to their
function
The following snippet will be inserted in your code:
My.Computer.FileSystem.WriteAllText(”C:\test.txt”, ”Text”, True)
To write some text to a ?le, you need to call the WriteAllText method of the My.Computer
.FileSystem object. You can replace the strings shown in the snippet with actual values. The ?rst
string is the ?lename, the second string is the text to be written to the ?le, and the last argument
of the method determines whether the text will be appended to the ?le (if False) or will overwrite
any existing text (if True).
The snippet shows you the basic statements for performing a common task, and you can edit
the code inserted by Visual Studio as needed. A real-world application would probably promptPetroutsos c01.tex V2 - 01/28/2008 11:43am Page 30
30 CHAPTER 1 GETTING STARTED WITH VISUAL BASIC 2008
the user for a ?lename via the File common dialog box and then use the ?lename speci?ed by the
user in the dialog box, instead of a hard-coded ?le name.
Figure 1.18
Selecting a code snippet
to insert in your code
As you program, you should always try to ?nd out whether there’s a snippet for the task at
hand. Sometimes you can use a snippet without even knowing how it works. Although snippets
can simplify your life, they won’t help you understand the Framework, which is discussed in
detail throughout this book.
Using theMyObject
You have probably noticed that the code snippets of Visual Studio use an entity called My, which
is a peculiar object that was introduced with VB 2005 to simplify many programming tasks. As
you saw in the preceding code snippet, the My object allows you to write some text to a ?le with
a single statement, the WriteAllText method. If you’re familiar with earlier versions of Visual
Basic, you know that you must ?rst open a ?le, and then write some text to it, and ?nally close the
?le. The My object allows you to perform all these operations with a single statement, as you saw
in the preceding example.
Another example is the Play method, which you can use to play back a WAV ?le from within
your code:
My.Computer.Audio.Play (”C:\Sounds\CountDown.wav”)
You can also use the following expression to play back a system sound:
My.Computer.Audio.PlaySystemSound(System.Media.SystemSounds.Exclamation)Petroutsos c01.tex V2 - 01/28/2008 11:43am Page 31
USING THE MY OBJECT 31
The method that plays back the sound is the Play method, and the method that writes text to
a ?le is the WriteAllText method. However, you can’t call them directly through the My object;
they’re not methods of the My object. If they were, you’d have to dig hard to ?nd out the method
you need. The My object exposes six components, which contain their own components. Here’s a
description of the basic components of the My object and the functionality you should expect to
?nd in each component:
My.Application The Application component provides information about the current appli-
cation. The CommandLineArgs property of My.Application returns a collection of strings, which
are the arguments passed to the application when it was started. TypicalWindows applications
aren’t called with command-line arguments, but it’s possible to start an application and pass a
?lename as an argument to the application (the document to be opened by the application, for
example). The Info property is an object that exposes properties such as DirectoryPath (the
application’s default folder), ProductName, Version,andsoon.
Computer This component of the My object exposes a lot of functionality via a number of
properties, many of which are objects. The My.Computer.Audio component lets you play back
sounds. The My.Computer.Clipboard component lets you access the Clipboard. To ?nd out
whether the Clipboard contains a speci?c type of data, use the ContainsText, ContainsImage,
ContainsData,and ContainsAudio methods. To retrieve the contents of the Clipboard, use
the GetText, GetImage, GetData,and GetAudioStream methods. Assuming that you have
a form with a TextBox control and a PictureBox control, you can retrieve text or image data
from the Clipboard and display it on the appropriate control with the following statements:
If My.Computer.Clipboard.ContainsImage Then
PictureBox1.Image = My.Computer.Clipboard.GetImage
End If
If My.Computer.Clipboard.ContainsText Then
TextBox2.Text = My.Computer.Clipboard.GetText
End If
You may have noticed that using the My object in your code requires that you write long
statements. You can shorten them substantially via the With statement, as shown next:
With My.Computer.Clipboard
If .ContainsImage Then
PictureBox1.Image = .GetImage
End If
If .ContainsText Then
TextBox2.Text = .GetText
End If
End With
When you’re executing multiple statements on the same object, you can specify the object in
a With statement and call its methods in the block of the With statement by specifying the
method name pre?xed with a period. The With statement is followed by the name of the object
to which all following methods apply, and is terminated with the End With statement.Petroutsos c01.tex V2 - 01/28/2008 11:43am Page 32
32 CHAPTER 1 GETTING STARTED WITH VISUAL BASIC 2008
Another property of the My.Computer component is the FileSystem object that exposes all
the methods you need to access ?les and folders. If you enter the expression My.Computer
.FileSystem followed by a period, you will see all the methods exposed by the FileSystem
component. Among them, you will ?nd DeleteFile, DeleteDirectory, RenameFile,
RenameDirectory, WriteAllText, ReadAllText, and many more. Select a method and then
type the opening parenthesis. You will see the syntax of the method in a ToolTip. The syntax of
the CopyFile method is as follows:
My.Computer.FileSystem.CopyFile(
sourceFileName As String, destinationFileName As String)
Just specify the path of the ?le you want to copy and the new ?le’s name, and you’re ?nished.
This statement will copy the speci?ed ?le to the speci?ed location.
You will notice that the ToolTip box with the syntax of the CopyFile method has multiple ver-
sions, which are listed at the left side of the box along with arrow up and arrow down icons.
Click these two buttons to see the next and previous versions of the method. The second ver-
sion of the CopyFile method is as follows:
My.Computer.FileSystem.CopyFile(
sourceFileName As String, destinationFileName As String,
overwrite As Boolean)
The overwrite argument speci?es whether the method should overwrite the destination ?le if
it exists.
The third version of the method accepts a different third argument that determines whether the
usual copy animation will be displayed as the ?le is being copied.
The various versions of the same method differ in the number and/or type of their arguments,
and they’re called overloaded forms of the method. Instead of using multiple method names
for the same basic operation, the overloaded forms of a method allow you to call the same
method name and adjust its behavior by specifying different arguments.
Forms This component lets you access the forms of the current application. You can also
access the application’s forms by name, so the Forms component isn’t the most useful one.
Settings This component lets you access the application settings. These settings apply to the
entire application and are stored in an XML con?guration ?le. The settings are created from
within Visual Studio, and you use the Settings component to read them.
User This component returns information about the current user. The most important
property of the User component is the CurrentPrincipal property, which is an object that
represents the credentials of the current user.
WebServices The WebServices component represents the web services referenced by the
current application.
The My object gives beginners unprecedented programming power and allows you to perform
tasks that would require substantial code if implemented with earlier versions of the language, not
to mention the research it would take to locate the appropriate methods in the Framework. You
can explore the My object on your own and use it as needed. My is not a substitute for learningPetroutsos c01.tex V2 - 01/28/2008 11:43am Page 33
THE BOTTOM LINE 33
the language and the Framework. It can help you initially, but you can’t go far without learning
the methods of the Framework for handling ?les or any other feature.
Let’s say you want to locate all the ?les of a speci?c type in a folder, including its subfolders.
Scanning a folder and its subfolders to any depth is quite a task (you’ll ?nd the code in Chapter
15, ‘‘Accessing Folders and Files’’). You can do the same with a single statement by using the
My object:
Dim files As ReadOnlyCollection(Of String)
files = My.Computer.FileSystem.GetFiles(”D:\Data”, True, ”*.txt”)
The GetFiles method populates the files collection with the pathnames of the text ?les in
the folder D:\Data and its subfolders. However, it won’t help you if you want to process each ?le
in place. Moreover, this GetFiles method is synchronous: If the folder contains many subfolders
with many ?les, it will block the interface until it retrieves all the ?les. In Chapter 15, you’ll see the
code that retrieves ?lenames and adds them to a control as it goes along.
If you’re already familiar with VB, you may think that the My object is an aid for the absolute
beginner or the nonprogrammer. This isn’t true. VB is about productivity, and the My object can
help you be more productive with your daily tasks, regardless of your knowledge of the language
or programming skills. If you can use My to save a few (or a few dozen) statements, do it. There’s
no penalty for using the My object, because the compiler replaces the methods of the My object
with the equivalent method calls to the Framework.
The BottomLine
Navigate the integrated development environment of Visual Studio. To simplify the pro-
cess of application development, Visual Studio provides an environment that’s common to
all languages, known as an integrated development environment (IDE). The purpose of the
IDE is to enable the developer to do as much as possible with visual tools, before writing code.
The IDE provides tools for designing, executing, and debugging your applications. It’s your
second desktop, and you’ll be spending most of your productive hours in this environment.
Master It Describe the basic components of the Visual Studio IDE.
Understand the basics of a Windows application. A Windows application consists of a
visual interface and code. The visual interface is what users see at runtime: a form with controls
with which the user can interact— by entering strings, checking or clearing check boxes, click-
ing buttons, and so on. The visual interface of the application is designed with visual tools. The
visual elements incorporate a lot of functionality, but you need to write some code to react to
user actions.
Master It Describe the process of building a simple Windows application.Petroutsos c01.tex V2 - 01/28/2008 11:43am Page 34Petroutsos c02.tex V2 - 01/28/2008 12:12pm Page 35
Chapter 2
Variables and Data Types
This chapter and the next discuss the fundamentals of any programming language: variables
and data types. A variable stores data, which are processed with statements. A program is a list
of statements that manipulate variables. To write even simple applications, you need a basic
understanding of some fundamental topics, such as the data types (the kind of data you can store
in a variable), the scope and lifetime of variables, and how to write procedures and pass arguments
to them. In this chapter, we’ll explore the basic data types of Visual Basic, and in the following one,
you’ll learn about procedures and ?ow-control statements.
If you’re new to Visual Basic, you may ?nd some material in this chapter less than exciting. It
covers basic concepts and de?nitions — in general, tedious, but necessary, material. Think of this
chapter as a prerequisite for the following ones. If you need information on core features of the
language as you go through the examples in the rest of the book, you’ll probably ?nd it here.
In this chapter, you’ll learn how to do the following:
? Declare and use variables
? Use the native data types
? Create custom data types
? Use arrays
Variables
In Visual Basic, as in any other programming language, variables store values during a program’s
execution. A variable has a name and a value. The variable UserName, for example, can have
the value Joe, and the variable Discount can have the value 0.35. UserName and Discount are
variable names, and Joe and 0.35 are their values. Joe is a string (that is, text or an alphanumeric
value), and 0.35 is a numeric value. When a variable’s value is a string, it must be enclosed in
double quotes. In your code, you can refer to the value of a variable by the variable’s name.
In addition to a name and a value, variables have a data type, which determines what kind
of values we can store to a variable. VB 2008 supports several data types (and they’re discussed
in detail later in this chapter). It’s actually the Common Language Runtime (CLR) that supports
the data types, and they’re common to all languages, not just to Visual Basic. The data type of a
variable is speci?ed when the variable is declared, and you should always declare variables before
using them. To declare a variable, enter the Dim statement, followed by the variable’s name, the As
keyword, and the variable’s type:
Dim Amount As DecimalPetroutsos c02.tex V2 - 01/28/2008 12:12pm Page 36
36 CHAPTER 2 VARIABLES AND DATA TYPES
Decimal is a numeric data type; it can store both integer and noninteger values. For example,
the following statements calculate and display the discount for the amount of $24,500:
Dim Amount As Decimal
Dim Discount As Decimal
Dim DiscountedAmount As Decimal
Amount = 24500
Discount = 0.35
DiscountedAmount = Amount * (1 - Discount)
MsgBox(”Your price is $” & DiscountedAmount.ToString)
If you enter these statements in a button’s Click event handler to test them, the compiler may
underline the statement that assigns the value 0.35 to the Discount variable and generate an
error message. To view the error message, hover the pointer over the underlined segment of the
statement in error. This will happen if the Strict option is on. (I discuss the Strict option, along with
two more options of the compiler, later in this chapter.) By default, the Strict option is off and the
statement should generate an error.
The compiler treats any numeric value with a fractional part as a Double value and detects that
you’re attempting to assign a Double value to a Decimal variable. To convert the numeric value to
the Decimal type, use the following notation:
Discount = 0.35D
As you will see later, the D character at the end of a numeric value indicates that the value
should be treated as a Decimal value, and there are a few more type characters (see Table 2.2 later
in this chapter). I’ve used the Decimal data type here because it’s commonly used in ?nancial
calculations. The message that this expression displays depends on the values of the Discount
and Amount variables. If you decide to offer a better discount, all you have to do is change the
value of the Discount variable. If you didn’t use the Discount variable, you’d have to make many
changes throughout your code. In otherwords, if you coded the line that calculated the discounted
amount as follows, you’d have to look for every line in your code that calculates discounts and
change the discount from 0.35 to another value:
DiscountedAmount = 24500 * (1 - 0.35)
By changing the value of the Discount variable in a single place in your code, the entire
program is up-to-date.
Declaring Variables
In most programming languages, variables must be declared in advance. Historically, the reason
for doing this has been to help the compiler generate the most ef?cient code. If the compiler knows
all the variables and their types ahead of time, it can produce the most compact and ef?cient, or
optimized, code. For example, when you tell the compiler that the variable Discount will hold a
number, the compiler sets aside a certain number of bytes for the Discount variable to use.
One of the most popular, yet intensely criticized, features of BASIC was that it didn’t force
the programmer to declare all variables. As you will see, there are more compelling reasons than
speed and ef?ciency for declaring variables. For example, when a compiler knows the types ofPetroutsos c02.tex V2 - 01/28/2008 12:12pm Page 37
VARIABLES 37
variables in advance, it can catch many errors at design or compile time — errors that otherwise
would surface at runtime. When you declare a variable as Date, the compiler won’t let you assign
an integer value to it.
When programming in VB 2008, you should declare your variables because this is the default
mode, and Microsoft recommends this practice strongly. If you attempt to use an undeclared
variable in your code, VB 2008 will throw an exception. It will actually catch the error as soon
as you complete the line that uses the undeclared variable, underlining it with a wiggly line. It
is possible to change the default behavior and use undeclared variables the way most people did
with earlier versions of VB (you’ll see how this is done in the section ‘‘The Strict, Explicit, and Infer
Options,’’ later in this chapter), but all the examples in this book use explicitly declared variables.
In any case, you’re strongly encouraged to declare your variables.
To declare a variable, use the Dim statement followed by the variable’s name, the As keyword,
and its type, as follows:
Dim meters As Integer
Dim greetings As String
The ?rst variable, meters, will store integers, such as 3 or 1,002; the second variable, greetings,
will store text. You can declare multiple variables of the same or different type in the same line, as
follows:
Dim Qty As Integer, Amount As Decimal, CardNum As String
If you want to declare multiple variables of the same type, you need not repeat the type. Just
separate all the variables of the same type with commas and set the type of the last variable:
Dim Length, Width, Height As Integer, Volume, Area As Double
This statement declares three Integer variables and two Double variables. Double variables
hold fractional values (or ?oating-point values, as they’re usually called) that are similar to the
Single data type, except that they can represent noninteger values with greater accuracy.
You can use other keywords in declaring variables, such as Private, Public,and Static.
These keywords are called access modi?ers because they determine which sections of your code
can access the speci?c variables and which sections can’t. You’ll learn about these keywords in
later sections of this chapter. In the meantime, bear in mind that all variables declared with the
Dim statement exist in the module in which they were declared. If the variable Count is declared
in a subroutine (an event handler, for example), it exists only in that subroutine. You can’t access
it from outside the subroutine. Actually, you can have a Count variable in multiple procedures.
Each variable is stored locally, and they don’t interfere with one another.
Variable-Naming Conventions
When declaring variables, you should be aware of a few naming conventions. A variable’s name
? Must begin with a letter, followed by more letters or digits.
? Can’t contain embedded periods or other special punctuation symbols. The only special
character that can appear in a variable’s name is the underscore character.
? Mustn’t exceed 255 characters.Petroutsos c02.tex V2 - 01/28/2008 12:12pm Page 38
38 CHAPTER 2 VARIABLES AND DATA TYPES
? Must be unique within its scope. This means that you can’t have two identically named
variables in the same subroutine, but you can have a variable named counter in many
different subroutines.
Variable names in VB 2008 are case-insensitive: myAge, myage,and MYAGE all refer to the same
variable in your code. Actually, as you enter variable names, the editor converts their casing so
that they match their declaration.
Variable Initialization
VB 2008 allows you to initialize variables in the same line that declares them. The following
statement declares an Integer variable and initializes it to 3,045:
Dim distance As Integer = 3045
This statement is equivalent to the following two:
Dim distance As Integer
distance = 3045
It is also possible to declare and initialize multiple variables, of the same or different type, on
the same line:
Dim quantity As Integer = 1, discount As Single = 0.25
Type Inference
As Imentioned earlier, one of the trademark features of BASIC, including earlier versions of Visual
Basic, was the ability to use variables without declaring them. It has never been a recommended
practice, yet VB developers loved it. This feature is coming back to the language, only in a safer
manner. VB 2008 allows you to declare variables by assigning values to them. The compiler will
infer the type of the variable from its value and will create a variable of the speci?c type behind
the scenes. The following statement creates an Integer variable:
Dim count = 2999
To request the variable’s type, use the GetType method. This method returns a Type object,
which represents the variable’s type. The name of the type is given by the ToString property. The
following statement will print the highlighted string in the Immediate window:
Debug.WriteLine(count.GetType.ToString)
System.Int32
The count variable is of the Integer type. If you attempt to assign a value of a different type to
this variable later in your code, such as a date, the editor will underline the value and generate
the warning Value of type ‘Date’ cannot be converted to Integer. The compiler has inferred the type
of the value assigned initially to the variable and created a variable of the same type. That’s why
subsequent statements can’t change the variable’s type. You can turn off type inference by
inserting the following statement at the top of the module:
Option Infer OffPetroutsos c02.tex V2 - 01/28/2008 12:12pm Page 39
VARIABLES 39
Alternatively, you can turn on or off this option in the project’s Properties pages. If the Infer
option is off, the compiler will handle variables declared without a speci?c type depending on
the Strict option. If the Strict option is off, the compiler will create an Object variable, which can
store any value, even values of different types in the course of the application. If the Strict option
is on, the compiler will reject the declaration; it will underline the variable’s name with a wiggly
line and generate the following warning: Option Strict On requires all variabledeclarationstohavean
As clause.
For more information on the various variable declaration–related options of the compiler, see
the section ‘‘The Strict, Explicit, and Infer Options,’’ later in this chapter. In the following sections,
you’ll explore the various data types of Visual Basic, and I will use explicit declarations, which is
the recommended best practice for creating and using variables in your code.
Types of Variables
Visual Basic recognizes the following ?ve categories of variables:
? Numeric
? String
? Boolean
? Date
? Object
The two major variable categories are numeric and string. Numeric variables store numbers,
and string variables store text. Object variables can store any type of data. Why bother to specify
the type if one type suits all? On the surface, using object variables might seem like a good idea,
but they have their disadvantages. Integer variables are optimized for storing integers, and date
variables are optimized for storing dates. Before VB can use an object variable, it must determine
its type and perform the necessary conversions. If the variable is declared with a speci?c type,
these conversions are not necessary.
We begin our discussion of variable types with numeric variables. Text is stored in string
variables, but numbers can be stored in many formats, depending on the size of the number and
its precision. That’s why there are many types of numeric variables. The String and Date data
types are much richer in terms of the functionality they expose, and are discussed in more detail
in Chapter 13, ‘‘Handling Strings, Characters, and Dates.’’
Numeric Variables
You’d expect that programming languages would use the same data type for numbers. After all,
a number is a number. But this couldn’t be further from the truth. All programming languages
provide a variety of numeric data types, including the following:
? Integers (there are several integer data types)
? Decimals
? Single, or ?oating-point numbers with limited precision
? Double, or ?oating-point numbers with extreme precision
Decimal, Single, and Double are the three basic data types for storing ?oating-point
numbers (numbers with a fractional part). The Double data type can represent these numbers
more accurately than the Single type and is used almost exclusively in scienti?c calculations.Petroutsos c02.tex V2 - 01/28/2008 12:12pm Page 40
40 CHAPTER 2 VARIABLES AND DATA TYPES
The Integer data types store whole numbers. The data type of your variable can make a
difference in the results of the calculations. The proper variable types are determined by the
nature of the values they represent, and the choice of data type is frequently a trade-off
between precision and speed of execution (less-precise data types are manipulated faster).
Visual Basic supports the numeric data types shown in Table 2.1. In the Data Type column,
I show the name of each data type and the corresponding keyword in parentheses.
Integer Variables
There are three types of variables for storing integers, and they differ only in the range of numbers
each can represent. As you understand, the more bytes a type takes, the larger values it can hold.
The type of Integer variable you’ll use depends on the task at hand. You should choose the type
that can represent the largest values you anticipate will come up in your calculations. You can go
for the Long type, to be safe, but Long variables are four times as large as Short variables, and it
takes the computer longer to process them.
The statements in Listing 2.1 will help you understand when to use the various Integer data
types. Each numeric data type exposes the MinValue and MaxValue properties, which return the
minimum and maximum values, respectively, that can be represented by the corresponding data
type. Values of the Short (Int16) type can be stored in Integer (Int32) and Long (Int64)variables,
but the reverse is not true. If you attempt to store a Long value to an Integer variable, an error will
be generated and the compiler will underline the offending line with a wiggly line. I have included
comments after each statement to explain the errors produced by some of the statements.
Listing 2.1: Experimentingwith the Ranges of Numeric Variables
Dim shortInt As Int16
Dim Int As Int32
Dim longInt As Int64
Debug.WriteLine(Int16.MinValue)
Debug.WriteLine(Int16.MaxValue)
Debug.WriteLine(Int32.MinValue)
Debug.WriteLine(Int32.MaxValue)
Debug.WriteLine(Int64.MinValue)
Debug.WriteLine(Int64.MaxValue)
shortInt = Int16.MaxValue + 1
’ ERROR, exceeds the maximum value of the Short data type
Int = Int16.MaxValue + 1
’ OK, is within the range of the Integer data type
Int = Int32.MaxValue + 1
’ ERROR, exceeds the maximum value of the Integer data type
Int = Int32.MinValue - 1
’ ERROR, exceeds the minimum value of the Integer data type
longInt = Int32.MaxValue + 1
’ OK, is within the range of the Long data type
longInt = Int64.MaxValue + 1
’ ERROR, exceeds the range of all Integer data typesPetroutsos c02.tex V2 - 01/28/2008 12:12pm Page 41
VARIABLES 41
Table 2.1: Visual Basic Numeric Data Types
Data Type Memory Representation Stores
Byte (Byte) 1 byte Integers in the range 0 to 255.
Signed Byte (SByte) 1 byte Integers in the range -128 to 127.
Short (Int16) 2 bytes Integer values in the range -32,768
to 32,767.
Integer (Int32) 4 bytes Integer values in the range
-2,147,483,648 to 2,147,483,647.
Long (Int64) 8 bytes Integer values in the range
-9,223,372,036,854,755,808 to
9,223,372,036,854,755,807.
Unsigned Short (UShort) 2 bytes Positive integer values in the range 0
to 65,535.
Unsigned Integer (UInteger) 4 bytes Positive integers in the range 0 to
4,294,967,295.
Unsigned Long (ULong) 8 bytes Positive integers in the range 0 to
18,446,744,073,709,551,615.
Single Precision (Single) 4 bytes Single-precision ?oating-point
numbers. It can represent negative
numbers in the range -3.402823E38
to -1.401298E-45 and positive
numbers in the range 1.401298E-45
to 3.402823E38. The value 0 can’t
be represented precisely (it’s a
very, very small number, but not
exactly 0).
Double Precision (Double) 8 bytes Double-precision ?oating-point
numbers. It can represent negative
numbers in the range
-1.79769313486232E308 to
-4.94065645841247E-324 and
positive numbers in the range
4.94065645841247E-324 to
1.79769313486232E308.
Decimal (Decimal) 16 bytes Integer and ?oating-point numbers
scaled by a factor in the range from
0 to 28. See the description of the
Decimal data type for the range of
values you can store in it.Petroutsos c02.tex V2 - 01/28/2008 12:12pm Page 42
42 CHAPTER 2 VARIABLES AND DATA TYPES
The six WriteLine statements will print the minimum and maximum values you can represent
with the various Integer data types. The following statement attempts to assign to a Short integer
variable a value that exceeds the largest possible value you can represent with the Short data type,
and it will generate an error. The editor will underline the incorrect statement, and if you hover
the pointer over the statement, you’ll see the error description: Constant expression not representable
in type Short. If you attempt to store the same value to an Integer variable, there will be no problem
because this value is well within the range of the Integer data type.
The next two statements attempt to store to an Integer variable two values that are also outside
of the range that an integer can represent. The ?rst value exceeds the range of positive values, and
the second exceeds the range of negative values. If you attempt to store these values to a Long
variable, there will be no problem. If you exceed the range of values that can be represented by
the Long data type, you’re out of luck. This value can’t be represented as an integer, and you must
store it in one of the variable types discussed in the next sections.
Single- and Double-Precision Numbers
The names Single and Double come from single-precision and double-precision numbers.
Double-precision numbers are stored internally with greater accuracy than single-precision
numbers. In scienti?c calculations, you need all the precision you can get; in those cases, you
should use the Double data type.
The result of the operation 1 / 3 is 0.333333... (an in?nite number of digits 3). You could ?ll
256MB of RAMwith 3 digits, and the result would still be truncated. Here’s a simple example that
demonstrates the effects of truncation:
In a button’s Click event handler, declare two variables as follows:
Dim a As Single, b As Double
Then enter the following statements:
a=1/3
Debug.WriteLine(a)
Run the application, and you should get the following result in the Output window:
.3333333
There are seven digits to the right of the decimal point. Break the application by pressing
Ctrl+Break and append the following lines to the end of the previous code segment:
a=a* 100000
Debug.WriteLine(a)
This time, the following value will be printed in the Output window:
33333.34Petroutsos c02.tex V2 - 01/28/2008 12:12pm Page 43
VARIABLES 43
The result is not as accurate as you might have expected initially — it isn’t even rounded
properly. If you divide a by 100,000, the result will be
0.3333334
This number is different from the number we started with (0.3333333). The initial value was
rounded when we multiplied it by 100,000 and stored it in a Single variable. This is an important
point in numeric calculations, and it’s called error propagation. In long sequences of numeric calcu-
lations, errors propagate. Even if you can tolerate the error introduced by the Single data type in a
single operation, the cumulative errors might be signi?cant.
Let’s perform the same operations with double-precision numbers, this time using the
variable b. Add these lines to the button’s Click event handler:
b=1/3
Debug.WriteLine(b)
b=b* 100000
Debug.WriteLine(b)
This time, the following numbers are displayed in the Output window:
0.333333333333333
33333.3333333333
The results produced by the double-precision variables are more accurate.
Why are such errors introduced in our calculations? The reason is that computers store
numbers internally with two digits: zero and one. This is very convenient for computers
because electronics understand two states: on and off. As a matter of fact, all the statements
are translated into bits (zeros and ones) before the computer can understand and execute them.
The binary numbering system used by computers is not much different from the decimal system
we humans use; computers just use fewer digits. We humans use 10 different digits to represent
any number, whole or fractional, because we have 10 ?ngers (in effect, computers count with
just two ?ngers). Just as with the decimal numbering system, in which some numbers can’t be
precisely represented, there are also numbers that can’t be represented precisely in the binary
system.
Let me give you a more illuminating example. Create a single-precision variable, a,anda
double-precision variable, b, and assign the same value to them:
Dim a As Single, b As Double
a = 0.03007
b = 0.03007
Then print their difference:
Debug.WriteLine(a-b)Petroutsos c02.tex V2 - 01/28/2008 12:12pm Page 44
44 CHAPTER 2 VARIABLES AND DATA TYPES
If you execute these lines, the result won’t be zero! It will be -6.03199004634014E-10. This is
a very small number that can also be written as 0.000000000603199004634014. Because different
numeric types are stored differently in memory, they don’t quite match. What this means to you
is that all variables in a calculation should be of the same type.
Eventually, computers will understand mathematical notation and will not convert all numeric
expressions into values, as they do today. If you multiply the expression 1/3 by 3, the result
should be 1. Computers, however, must convert the expression 1/3 into a value before they can
multiply it by 3. Because 1/3 can’t be represented precisely, the result of the (1/3) × 3 will not be
exactly 1. If the variables a and b are declared as Single or Double, the following statements will
print 1:
a=3
b=1/a
Debug.WriteLine(a * b)
If the two variables are declared as Decimal, however, the result will be a number very close
to 1, but not exactly 1 (it will be 0.9999999999999999999999999999— there are 28 digits after the
decimal point).
The Decimal Data Type
Variables of the Decimal type are stored internally as integers in 16 bytes and are scaled by a power
of 10. The scaling power determines the number of decimal digits to the right of the ?oating point,
and it’s an integer value from 0 to 28. When the scaling power is 0, the value is multiplied by
100
, or 1, and it’s represented without decimal digits. When the scaling power is 28, the value is
divided by 1028 (which is 1 followed by 28 zeros — an enormous value), and it’s represented with
28 decimal digits.
The largest possible value you can represent with a Decimal value is an integer: 79,228,162,
514,264,337,593,543,950,335. The smallest number you can represent with a Decimal variable is
the negative of the same value. These values use a scaling factor of 0. When the scaling factor
is 28, the largest value you can represent with a Decimal variable is quite small, actually. It’s
7.9228162514264337593543950335 (and the smallest value is the same with a minus sign). This
is a very small numeric value (not quite 8), but it’s represented with extreme accuracy. The
number zero can’t be represented precisely with a Decimal variable scaled by a factor of 28.
The smallest positive value you can represent with the same scaling factor is 0.00...01
(there are 27 zeros between the decimal period and the digit 1) — an extremely small value,
but still not quite zero. The more accuracy you want to achieve with a Decimal variable, the
smaller the range of available values you have at your disposal — just as with everything else
in life.
When using decimal numbers, the compiler keeps track of the decimal digits (the digits
following the decimal point) and treats all values as integers. The value 235.85 is represented
as the integer 23585, but the compiler knows that it must scale down the value by 100 when
it ?nishes using it. Scaling down by 100 (that is, 102) corresponds to shifting the decimal
point by two places. First, the compiler multiplies this value by 100 to make it an integer. Then,
it divides it by 100 to restore the original value. Let’s say that you want to multiply the following
values:
328.558 * 12.4051Petroutsos c02.tex V2 - 01/28/2008 12:12pm Page 45
VARIABLES 45
First, you must turn them into integers. You must remember that the ?rst number has three
decimal digits, and the second number has four decimal digits. The result of the multiplication
will have seven decimal digits. So you can multiply the following integer values:
328558 * 124051
and then treat the last seven digits of the result as decimals. Use the Windows Calculator (in
the Scienti?c view) to calculate the previous product. The result is 40,757,948,458. The actual
value after taking into consideration the decimal digits is 4,075.7948458. This is how the compiler
manipulates the Decimal data type. Insert the following lines in a button’s Click event handler
and execute the program:
Dim a As Decimal = 328.558D
Dim b As Decimal = 12.4051D
Dim c As Decimal
c=a*b
Debug.WriteLine(c.ToString)
The D character at the end of the two numeric values speci?es that the numbers should be
converted into Decimal values. By default, every value with a fractional part is treated as a Double
value. Assigning a Double value to a Decimal variable will produce an error if the Strict option is
on, so we must specify explicitly that the two values should be converted to the Decimal type. The
D character at the end of the value is called a type character. Table 2.2 lists all of them.
Table 2.2: Type Characters
Type Character Description Example
C Converts value to a Char type Dim ch As String = ‘‘A’’c
D or @ Converts value to a Decimal type Dim price As Decimal = 12.99D
R or # Converts value to a Double type Dim pi As Double = 3.14 R
I or % Converts value to an Integer type Dim count As Integer = 99I
L or & Converts value to a Long type Dim distance As Long = 1999L
S Converts value to a Short type Dim age As Short = 1S
F or ! Converts value to a Single type Dim velocity As Single = 74.99F
If you perform the same calculations with Single variables, the result will be truncated (and
rounded) to three decimal digits: 4,075.795. Notice that the Decimal data type didn’t introduce
any rounding errors. It’s capable of representing the result with the exact number of decimal
digits. This is the real advantage of Decimals, which makes them ideal for ?nancial applications.
For scienti?c calculations, you must still use Doubles. Decimal numbers are the best choice for
calculations that require a speci?c precision (such as four or eight decimal digits).Petroutsos c02.tex V2 - 01/28/2008 12:12pm Page 46
46 CHAPTER 2 VARIABLES AND DATA TYPES
In?nity and Other Oddities
The Framework can represent two very special values, which may not be numeric values
themselves but are produced by numeric calculations: NaN (not a number) and In?nity. If your
calculations produce NaN or In?nity, you should con?rm the data and repeat the calculations,
or give up. For all practical purposes, neither NaN nor In?nity can be used in everyday business
calculations.
Not a Number (NaN)
NaN is not new. Packages such as Wolfram Mathematica and Microsoft Excel have been using
it for years. The value NaN indicates that the result of an operation can’t be de?ned: It’s not a
regular number, not zero, and not in?nity. NaN ismore of amathematical concept rather than a value
you can use in your calculations. The Log() function, for example, calculates the logarithm of
positive values. By de?nition, you can’t calculate the logarithm of a negative value. If the argument
you pass to the Log() function is a negative value, the function will return the value NaN to indicate
that the calculations produced an invalid result. You may ?nd it annoying that a numeric function
returns a non-numeric value, but it’s better than throwing an exception. Even if you don’t detect this
condition immediately, your calculations will continue and they will all produce NaN values.
Some calculations produce unde?ned results, such as in?nity. Mathematically, the result of
dividing any number by zero is in?nity. Unfortunately, computers can’t represent in?nity, so they
produce an error when you request a division by zero. VB 2008 will report a special value, which
isn’t a number: the In?nity value. If you call the ToString method of this value, however, it will
return the string Infinity. Let’s generate an Infinity value. Start by declaring a Double variable,
dblVar:
Dim dblVar As Double = 999
Then divide this value by zero:
Dim infVar as Double
infVar = dblVar / 0
and display the variable’s value:
MsgBox(infVar)
The string Infinity will appear in a message box. This string is just a description; it tells you
that the result is not a valid number (it’s a very large number that exceeds the range of numeric
values that can be represented with any data type), but it shouldn’t be used in other calculations.
However, you can use the In?nity value in arithmetic operations. Certain operations with in?nity
make sense; others don’t. If you add a number to in?nity, the result is still in?nity (any number,
even an arbitrarily large one, can still be increased). If you divide a value by in?nity, you’ll get
the zero value, which also makes sense. If you divide one In?nity value by another In?nity value,
you’ll get the second odd value, NaN.Petroutsos c02.tex V2 - 01/28/2008 12:12pm Page 47
VARIABLES 47
Another calculation that will yield a non-number is the division of a very large number by a
very small number. If the result exceeds the largest value that can be represented with the Double
data type, the result is Infinity. Declare three variables as follows:
Dim largeVar As Double = 1E299
Dim smallVar As Double = 1E-299
Dim result As Double
The notation 1E299 means 10 raised to the power of 299, which is an extremely large number.
Likewise, 1E-299 means 10 raised to the power of -299, which is equivalent to dividing 10 by a
number as large as 1E299.
Then divide the large variable by the small variable and display the result:
result = largeVar / smallVar
MsgBox(result)
The result will be In?nity. If you reverse the operands (that is, you divide the very small by the
very large variable), the result will be zero. It’s not exactly zero, but the Double data type can’t
accurately represent numeric values that are very, very close to zero.
You can also produce an In?nity value by multiplying a very large (or very small) number by
itself many times. But clearly, the most absurd method of generating an In?nity value is to assign
the Double.PositiveIn?nity or Double.NegativeIn?nity value to a variable!
The result of the division 0 / 0, for example, is not a numeric value. If you attempt to enter the
statement 0/0 in your code, however, VB will catch it even as you type, and you’ll get the error
message Division by zero occurs in evaluating this expression.
To divide zero by zero, set up two variables as follows:
Dim var1, var2 As Double
Dim result As Double
var1 = 0
var2 = 0
result = var1 / var2
MsgBox(result)
If you execute these statements, the result will be NaN. Any calculations that involve the result
variable will yield NaN as a result. The following statements will produce a NaN value:
result = result + result
result = 10 / result
result = result + 1E299
MsgBox(result)
If you make var2 a very small number, such as 1E-299, the result will be zero. If you make var1
a very small number, the result will be In?nity.
For most practical purposes, In?nity is handled just like NaN. They’re both numbers that
shouldn’t occur in business applications (unless you’re projecting the national de?cit in thePetroutsos c02.tex V2 - 01/28/2008 12:12pm Page 48
48 CHAPTER 2 VARIABLES AND DATA TYPES
next 50 years), and when they do, it means that you must double-check your code or your data.
They are much more likely to surface in scienti?c calculations, and they must be handled
with the statements described in the next section.
Testing for In?nity and NaN
To ?nd out whether the result of an operation is a NaN or In?nity, use the IsNaN
and IsInfinity methods of the Single and Double data types. The Integer data
type doesn’t support these methods, even if it’s possible to generate In?nity and NaN
results with integers. If the IsInfinity method returns True, you can further examine
the sign of the In?nity value with the IsNegativeInfinity and IsPositiveInfinity
methods.
In most situations, you’ll display a warning and terminate the calculations. The statements
of Listing 2.2 do just that. Place these statements in a button’s Click event handler and run the
application.
Listing 2.2: Handling NaN and In?nity Values
Dim var1, var2 As Double
Dim result As Double
var1 = 0
var2 = 0
result = var1 / var2
If Double.IsInfinity(result) Then
If Double.IsPositiveInfinity(result) Then
MsgBox(”Encountered a very large number. Can’t continue”)
Else
MsgBox(”Encountered a very small number. Can’t continue”)
End If
Else
If Double.IsNaN(result) Then
MsgBox(”Unexpected error in calculations”)
Else
MsgBox(”The result is:”& result.ToString)
End If
End If
This listing will generate a NaN value. Set the value of the var1 variable to 1 to generate
a positive In?nity value, or to -1 to generate a negative In?nity value. As you can see, the
IsInfinity, IsPositiveInfinity, IsNegativeInfinity,and IsNaN methods require that the
variable be passed as an argument.
If you change the values of the var1 and var2 variables to the following values and execute the
application, you’ll get the message Encountered a very large number:
var1 = 1E+299
var2 = 1E-299Petroutsos c02.tex V2 - 01/28/2008 12:12pm Page 49
VARIABLES 49
If you reverse the values, you’ll get the message Encountered a very small number. In any case,
the program will terminate gracefully and let you know the type of problem that prevents the
completion of the calculations.
Byte Variables
None of the previous numeric types is stored in a single byte. In some situations, however, data
are stored as bytes, and you must be able to access individual bytes. The Byte data type holds
an integer in the range of 0 to 255. Bytes are frequently used to access binary ?les, image and
sound ?les, and so on. Note that you no longer use bytes to access individual characters. Unicode
characters are stored in two bytes.
To declare a variable as a Byte, use the following statement:
Dim n As Byte
The variable n can be used in numeric calculations too, but you must be careful not to assign the
result to another Byte variable if its value might exceed the range of the Byte type. If the variables
A and B are initialized as follows:
Dim A As Byte, B As Byte
A = 233
B=50
the following statement will produce an over?ow exception:
Debug.WriteLine(A + B)
The same will happen if you attempt to assign this value to a Byte variable with the following
statement:
B=A+B
The result (283) can’t be stored in a single byte. Visual Basic generates the correct answer, but
it can’t store it into a Byte variable.
Boolean Operations with Bytes
The operators that won’t cause over?ows are the Boolean operators AND, OR, NOT,and XOR,which
are frequently used with Byte variables. These aren’t logical operators that return True or False;
they combine the matching bits in the two operands and return another byte. If you combine the
numbers 199 and 200 with the AND operator, the result is 192. The two values in binary format
are 11000111 and 11001000. If you perform a bitwise AND operationonthesetwovalues,theresultis
11000000, which is the decimal value 192.
In addition to the Byte data type, VB 2008 provides a Signed Byte data type, SByte, which can
represent signed values in the range from -128 to 127. The bytes starting with the 1 bit represent
negative values. The range of positive values is less by one than the range of values of negative
values, because the value 0 is considered a positive value (its ?rst bit is 0).Petroutsos c02.tex V2 - 01/28/2008 12:12pm Page 50
50 CHAPTER 2 VARIABLES AND DATA TYPES
Boolean Variables
The Boolean data type stores True/False values. Boolean variables are, in essence, integers that
take the value -1 (for True) and 0 (for False). Actually, any nonzero value is considered True.
Boolean variables are declared as
Dim failure As Boolean
and they are initialized to False. Boolean variables are used in testing conditions, such as the
following:
Dim failure As Boolean = False
’ other statements ...
If failure Then MsgBox(”Couldn’t complete the operation”)
They are also combined with the logical operators And, Or, Not,and Xor.The Not operator
toggles the value of a Boolean variable. The following statement is a toggle:
running = Not running
If the variable running is True, it’s reset to False, and vice versa. This statement is a shorter
way of coding the following:
Dim running As Boolean
If running = True Then
running = False
Else
running = True
End If
Boolean operators operate on Boolean variables and return another Boolean as their result. The
following statements will display a message if one (or both) of the variables ReadOnly and Hidden
are True (presumably these variables represent the corresponding attributes of a ?le):
If ReadOnly Or Hidden Then
MsgBox(”Couldn’t open the file”)
Else
{ statements to open and process file}
End If
The condition of the If statement combines the two Boolean values with the Or operator.
If one or both of them are True, the parenthesized expression is True. This value is negated with
the Not operator, and the If clause is executed only if the result of the negation is True. If ReadOnly
is True and Hidden is False, the expression is evaluated as
If Not (True Or False)Petroutsos c02.tex V2 - 01/28/2008 12:12pm Page 51
VARIABLES 51
(True Or False) is True, which reduces the expression to
If Not True
which, in turn, is False.
String Variables
The String data type stores only text, and string variables are declared as follows:
Dim someText As String
You can assign any text to the variable someText. You can store nearly 2GB of text in a string
variable (that’s 2 billion characters, and is much more text than you care to read on a computer
screen). The following assignments are all valid:
Dim aString As String
aString = ”Now is the time for all good men to come ” &
” to the aid of their country”
aString = ””
aString = ”There are approximately 25,000 words in this chapter”
aString = ”25,000”
The second assignment creates an empty string, and the last one creates a string that just
happens to contain numeric digits, which are also characters. The difference between these two
variables is that they hold different values:
Dim aNumber As Integer = 25000
Dim aString As String = ”25,000”
The aString variable holds the characters 2, 5, comma, 0, 0, and 0; and aNumber holds a
single numeric value. However, you can use the variable aString in numeric calculations, and the
variable aNumber in string operations. VB will perform the necessary conversions as long as the
Strict option is off.
The String data type and its text manipulation methods are discussed in detail in
Chapter 13.
Character Variables
Character variables store a single Unicode character in two bytes. In effect, characters are
Unsigned Short integers (UInt16); you can use the CChar() function to convert integers
to characters and use the CInt() function to convert characters to their equivalent
integer values.
To declare a Character variable, use the Char keyword:
Dim char1, char2 As CharPetroutsos c02.tex V2 - 01/28/2008 12:12pm Page 52
52 CHAPTER 2 VARIABLES AND DATA TYPES
You can initialize a Character variable by assigning either a character or a string to it. In the
latter case, only the ?rst character of the string is assigned to the variable. The following statements
will print the characters a and A to the Output window:
Dim char1 As Char = ”a”, char2 As Char = ”ABC”
Debug.WriteLine(char1)
Debug.WriteLine(char2)
These statements will work only if the Strict option is off. If it’s on, the values assigned to the
char1 and char2 variables will be marked in error. To ?x the error that prevents the compilation
of the code, change the Dim statement as follows:
Dim char1 As Char = ”a”c, char2 As Char = ”A”c
When the Strict option is on, you can’t assign a string to a Char variable and expect that only
the ?rst character of the string will be used.
The Integer values that correspond to the English characters are the ANSI (American National
Standards Institute) codes of the equivalent characters. The following statement will print the
value 65:
Debug.WriteLine(Convert.ToInt32(”a”))
If you convert the Greek character alpha (a) to an integer, its value is 945. The Unicode value of
the famous character p is 960.
Character variables are used in conjunction with strings. You’ll rarely save real data as char-
acters. However, you might have to process the individual characters in a string, one at a time.
The Char data type exposes a number of interesting methods for manipulating characters, and
they’re presented in detail in Chapter 13. Let’s say the string variable password holds a user’s new
password, and you require that passwords contain at least one special symbol. The code segment
of Listing 2.3 scans the password and rejects it if it contains letters and digits only.
Listing 2.3: Processing Individual Characters
Dim password As String, ch As Char
Dim i As Integer
Dim valid As Boolean = False
While Not valid
password = InputBox(”Please enter your password”)
For i = 0 To password.Length - 1
ch = password.Chars(i)
If Not Char.IsLetterOrDigit(ch) Then
valid = True
Exit For
End If
Next
If valid Then
MsgBox(”You new password will be activated immediately!”)Petroutsos c02.tex V2 - 01/28/2008 12:12pm Page 53
VARIABLES 53
Else
MsgBox(”Your password must contain at least one special symbol!”)
End If
End While
If you are not familiar with the If...Then, For...Next,or While...End While structures, you
can read their descriptions in the following chapter.
Thecodepromptstheuserwithaninputboxtoenterapassword.The valid variable is Boolean
and it’s initialized to False. (You don’t have to initialize a Boolean variable to False because this is
its default initial value, but it does make the code easier to read.) It’s set to True from within the
body of the loop, only if the password contains a character that is not a letter or a digit. We set it
to False initially, so the While...End While loop will be executed at least once. This loop will keep
prompting the user until a valid password is entered.
The For...Next loop scans the string variable password, one letter at a time. At each iteration,
the next letter is copied into the ch variable. The Chars property of the String data type is an array
that holds the individual characters in the string (another example of the functionality built into
the data types).
Then the program examines the current character. The IsLetterOrDigit method of the Char
data type returns True if a character is either a letter or a digit. If the current character is a symbol,
the program sets the valid variable to True so that the outer loop won’t be executed again, and
it exits the For...Next loop. Finally, it prints the appropriate message, and either prompts for
another password or quits.
The Char class and its methods are discussed in more detail in Chapter 13.
Date Variables
Date and time values are stored internally in a special format, but you don’t need to know the
exact format. They are double-precision numbers: the integer part represents the date, and the
fractional part represents the time. A variable declared as Date with a statement like the following
can store both date and time values:
Dim expiration As Date
The following are all valid assignments:
expiration = #01/01/2008#
expiration = #8/27/2008 6:29:11 PM#
expiration = ”July 2, 2008”
expiration = Today()
By the way, the Today() function returns the current date and time, while the Now() function
returns the current date. You can also retrieve the current date by calling the Today property of
the Date data type: Date.Today.
The pound sign tells Visual Basic to store a date value to the expiration variable,justasthe
quotes tell Visual Basic that the value is a string. You can store a date as a string to a Date variable,
but it will be converted to the appropriate format. If the Strict option is on, you can’t specify dates
by using the Long date format (as in the third statement of this example).Petroutsos c02.tex V2 - 01/28/2008 12:12pm Page 54
54 CHAPTER 2 VARIABLES AND DATA TYPES
The date format is determined by the Regional Settings (found in the Control Panel). In the
United States, the format is mm/dd/yy. (In other countries, the format is dd/mm/yy.) If you assign
an invalid date to a date variable, such as 23/04/2002, the statement will be underlined and an
error message will appear in the Task List window. The description of the error is Date constant is
not valid.
The Date data type is extremely ?exible; Visual Basic knows how to handle date and time
values, so you won’t have to write complicated code to perform the necessary conversions. To
manipulate dates and times, use the members of the Date type, which are discussed in detail in
Chapter 13, or the date and time functions of VB 6, which are still supported by VB 2008.
You can also perform arithmetic operations with date values. VB recognizes your intention to
subtract dates and it properly evaluates their difference. The result is a TimeSpan object, which
represents a time interval. If you execute the following statements, the value 638.08:49:51.4970000
will appear in the Output window:
Dim d1, d2 As Date
d1 = Now
d2 = #1/1/2004#Debug.WriteLine(d1 - d2)
The value of the TimeSpan object represents an interval of 638 days, 8 hours, 49 minutes, and
51.497 seconds.
Data Type Identi?ers
Finally, you can omit the As clause of the Dim statement, yet create typed variables, with the
variable declaration characters, or data type identi?ers. These characters are special symbols that
you append to the variable name to denote the variable’s type. To create a string variable, you can
use this statement:
Dim myText$
The dollar sign signi?es a string variable. Notice that the name of the variable includes
the dollar sign — it’s myText$,not myText. To create a variable of a particular type, use
one of the data declaration characters shown in Table 2.3. (Not all data types have their own
identi?ers.)
Using type identi?ers doesn’t help to produce the cleanest and easiest-to-read code. They’re
relics from really old versions of BASIC, and if you haven’t used them in the past, there’s no really
good reason to start using them now.
The Strict, Explicit, and Infer Options
The Visual Basic compiler provides three options that determine how it handles variables:
? The Explicit option indicates whether you will declare all variables.
? The Strict option indicates whether all variables will be of a speci?c type.
? The Infer option indicates whether the compiler should determine the type of a variable
from its value.
These options have a profound effect on the way you declare and use variables, and you should
understand what they do. By exploring these settings, you will also understand a little better howPetroutsos c02.tex V2 - 01/28/2008 12:12pm Page 55
VARIABLES 55
Table 2.3: Data Type De?nition Characters
Symbol Data Type Example
$ String A$, messageText$
% Integer (Int32) counter%, var%
& Long (Int64) population&, colorValue&
! Single distance!
# Double ExactDistance
@ Decimal Balance@
the compiler handles variables. It’s recommended that you turn on all three of them, but old VB
developers may not follow this advice.
VB 2008 doesn’t require that you declare your variables, but the default behavior is to throw an
exception if you attempt to use a variable that hasn’t been previously declared. If an undeclared
variable’s name appears in your code, the editor will underline the variable’s name with a wiggly
line, indicating that it caught an error. The description of the error will appear in the Task List
below the code window. If you rest the pointer over the segment of the statement in question, you
will see the description of the error in a ToolTip box.
To change the default behavior, you must insert the following statement at the beginning of
the ?le:
Option Explicit Off
The Option Explicit statement must appear at the very beginning of the ?le. This setting
affects the code in the current module, not in all ?les of your project or solution. You can turn
on the Strict (as well as the Explicit) option for an entire solution. Open the solution’s properties
dialog box (right-click the solution’s name in Solution Explorer and select Properties), select the
Compile tab, and set the Strict and Explicit options accordingly, as shown in Figure 2.1.
You can also set default values for the Explicit option (as well as for Strict and Infer) for
all projects through the Options dialog box of the IDE. To open this dialog box, choose the
Options command from the Tools menu. When the dialog box appears, select the VB Defaults tab
under Projects And Solutions, as shown in Figure 2.2. Here you can set the default values for all
four options. You can still change the default values for speci?c projects through the project’s
Properties pages.
The way undeclared variables are handled by VB 2008 is determined by the Explicit and Strict
options, which can be either on or off. The Explicit option requires that all variables used in the
code are declared before they’re used. The Strict option requires that variables are declared with a
speci?c type. In other words, the Strict option disallows the use of generic variables that can store
any data type. 

Make a Free Website with Yola.