Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

CH04 NutsBolts

Download as pdf or txt
Download as pdf or txt
You are on page 1of 52

Visual Basic .

NET Nuts and Bolts

Visual Basic .NET


Nuts and Bolts
Objectives
• Create a simple application using Notepad and the vbc compiler.
• Learn how settings in the Visual Studio .NET environment can affect
your code.
• Learn about the data types and syntax found in Visual Basic .NET.

The files associated with this chapter are located in the following directories:
○ VB.NET\NutsBolts
○ VB.NETLabs\NutsBoltsLab
○ VB.NETLabs\NutsBoltsLabCompleted

AppDev Sample Chapter--For Review Purposes Only 4-1


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Visual Basic .NET Nuts and Bolts

Creating Simple Applications


Visual Basic .NET is the first version of Visual Basic that allows you to
directly create and compile simple command line applications. A command
line application does not have a fancy user interfaceit is simply a program
that executes at the command prompt and requires only a minimal user
interface.

The Command Line Compiler (vbc.exe)


Almost all of the examples in this course are created and compiled in Visual
Studio .NET. However, you should be aware that this is not your only option.
The .NET Framework also ships with a command line compiler, vbc.exe. With
the command line compiler, which is a free download from Microsoft, you can
build Visual Basic .NET applications with only a copy of Notepad and the
.NET Framework. All types of applications, including console, Windows, and
Web applications, can be created using the command line compiler.

Open a Command Prompt window and type vbc. You will see all of the
switches and options for the command line compiler, as shown in Figure 1.

Figure 1. The Command window displays the switches for the command line
compiler.

We’re not going to cover all of the compiler options beyond creating a basic
Hello World console applicationyou can explore these for yourself by
simply reading the output shown in Figure 1. If you need a complete listing
with more detailed information than you see in the Command Prompt window,
you can search the online Help for “compiler options.”

Once you’ve configured the compiler, you can create a simple application.
You can create the following types of applications:

4-2 AppDev Sample Chapter--For Review Purposes Only


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Creating Simple Applications

• An EXE or DOS-style application, is the default when using the


command line compiler. This kind of application is run from the
command prompt and is also known as a console application.
• A library, or single-file DLL assembly, with a related manifest.
• A module, or a DLL, that does not contain a manifest and will be part
of a multi-file assembly.
• A Windows application, or EXE that has a user interface.
In short, you can use the compiler to create almost any type of application.

TIP: If working with Notepad and the Command Prompt window is not your cup
of tea, you can simply use Visual Studio .NET to create and compile all these
types of applications, and that’s what the bulk of this course focuses on.

AppDev Sample Chapter--For Review Purposes Only 4-3


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Visual Basic .NET Nuts and Bolts

Key Terms

Namespace A namespace in the .NET Framework is a hierarchical


organization of types within code assemblies. There are four
kinds of types: classes, interfaces, structures, and enumerations.
A namespace is a way of uniquely identifying things in order to
avoid naming conflicts. In other words, a Person class in
MyNamespace isn’t going to conflict with a Person class in
YourNamespace. You usually use the Imports statement in
your code to bypass having to type out the full namespace in
your code.

Assembly An assembly is a unit of executable code, usually in the form of


DLLs and EXE files. It contains the executable files, resources,
and a manifest describing the assembly’s contents. In .NET, you
can use an assembly without having to run a setup program.
Assemblies can be copied to a new location to be deployedthe
.NET Framework handles the runtime issues. In Visual Studio
.NET, each project creates an assembly.

Manifest The manifest is a data structure that contains information, or


metadata, about an assembly. The manifest makes the assembly
self-describing and self-containedyou no longer need to create
registry entries in order to execute your code. In its simplest
form, deploying an assembly can consist of simply copying the
file or files needed to run the application.

Try It Out!
Follow these steps to build a simple Hello World console application with
Notepad and vbc.exe:

1. Open Notepad and type the following:

' This is a comment


Module Module1
Public Sub Main
System.Console.WriteLine("Hello World")
End Sub
End Module

4-4 AppDev Sample Chapter--For Review Purposes Only


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Creating Simple Applications

Note that comments in Visual Basic .NET start with a single quote
character and are ignored by the compiler. The single line of code in
the application, the WriteLine method, works because the
System.Console reference tells the compiler where to look for the
WriteLine method. The classes in the System namespace are found in
the mscorlib.dll, which is the big enchilada of the .NET Framework.
You’ll learn more about namespaces and base classes later in the
course, but for now it’s enough to know that this is what makes the
code happen when you compile and run it.

2. Save the text file as:

c:\HelloWorld.vb

3. From the Windows Start menu, choose Programs|Microsoft Visual


Studio .NET|Visual Studio .NET Tools|Visual Studio .NET
Command Prompt and type the following statement. Press ENTER
when done.

vbc HelloWorld.vb

4. This compiles your application, as shown in Figure 2. Without


specifying any compiler options, the default is to create a console
application.

Figure 2. Compiling your console application.

AppDev Sample Chapter--For Review Purposes Only 4-5


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Visual Basic .NET Nuts and Bolts

5. To run the application, simply type HelloWorld at the command


prompt and press ENTER. The output from the application (the single
WriteLine statement), is displayed immediately beneath the
HelloWorld command, as shown in Figure 3.

Figure 3. Executing the HelloWorld console application.

4-6 AppDev Sample Chapter--For Review Purposes Only


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Getting Started with Visual Basic .NET in Visual Studio .NET

Getting Started with Visual Basic .NET


in Visual Studio .NET
In this course, you’ll be working with Visual Basic .NET using Visual Studio
.NET, so it’s important to understand how to configure your environment.
What you see on the menus in Visual Studio .NET and how your Visual Basic
.NET code behaves depends very much on these configuration settings. Many
of these settings are saved in XML configuration files and Visual Studio .NET
provides a handy user interface for manipulating them.

The Start Page


The Start Page comes up when you first launch Visual Studio .NET. It displays
the project files on the Projects tab, and more importantly, the Find Samples
tab, which allows you to configure options depending on which language you
are programming in.

TIP: Most of the options on the Start Page can also be found on the main File
menu.

Figure 4 shows the Start page with the Find Samples tab selected. You can
search on any keyword and a list of relevant topics will be displayed.

Figure 4. The Find Samples tab lets you search for code samples based on the
language you are programming in.

AppDev Sample Chapter--For Review Purposes Only 4-7


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Visual Basic .NET Nuts and Bolts

Click the My Profile link displayed in the lower left-hand corner of Figure 4.
This takes you to the Profile page, where you configure options shown in
Figure 5.

Figure 5. The My Profile link lets you configure your profile for Visual Studio
.NET.

The profile you select will reflect your comfort levelhere are the options you
can choose from:

• Visual Studio Developer


• Visual Basic Developer
• Visual C++ Developer
• Visual InterDev Developer
• VS Macro Developer
• Student Developer
• Visual C# Developer
• (custom)

This courseware is based on the Visual Basic Developer option, which will
give you all of the same shortcut keys that you are already familiar with if you
are a Visual Basic 6 programmer migrating to .NET. If you choose one of the
other options, some of the instructions you may see in other chapters will not
work.

4-8 AppDev Sample Chapter--For Review Purposes Only


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Getting Started with Visual Basic .NET in Visual Studio .NET

Creating a New Visual Basic .NET


Project
To create a new project in Visual Studio .NET, click the New Project button
on the Start page. Or choose File|New|Project from the menu. Either method
will load the New Project dialog box where you can choose Windows
Application from the available options. A Windows Application is a Windows
Forms application, where you can build a graphical user interface and code in
Visual Studio .NET. Windows Forms applications are going to be the main
focus in this course.

See NutsBolts.sln When you create a Windows application, you will see the project listed in the
Solution Explorer shown in Figure 6. A solution can contain one or more
projects, although in this case it only contains one, NutsBolts.

Figure 6. Files listed in the Solution Explorer.

When you save your project, the files are saved separately to disk, as shown in
Figure 7. The solution file, or NutsBolts.sln, is used to load the other files that
comprise the solution. Note that all code, whether in a form or a module, is
saved in a file with a .vb extension.

Figure 7. Files saved with a solution.

AppDev Sample Chapter--For Review Purposes Only 4-9


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Visual Basic .NET Nuts and Bolts

Project Properties
The Project Properties dialog box provides settings that are configurable at the
project level. Unlike your profile, which applies to all of Visual Studio .NET,
project properties apply only to the project they are set for.

Right-click on the project name in the Solution Explorer and choose


Properties from the menu or click the Properties button in the Solution
Explorer. Figure 8 shows the property settings on the General tab. Note that
the assembly name and root namespace default to the name of the project.

Figure 8. Project property settings on the General tab.

For a Windows project, you need to designate either a startup form (frmMain
is shown in Figure 8), or a procedure named Main(), which you write yourself
and that executes when the application starts.

4-10 AppDev Sample Chapter--For Review Purposes Only


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Getting Started with Visual Basic .NET in Visual Studio .NET

Option Explicit and Option Strict


The Build tab, shown in Figure 9, is where you set two other important
references, Option Explicit and Option Strict. These two properties have
important implications for the way in which code behaves.

Figure 9. Setting Option Explicit and Option Strict to On will save you time when
debugging code later.

Option Explicit
Visual Basic .NET has its roots in VBA, or Visual Basic for Applications,
which in turn has its roots in the old BASIC programming language. In the old
BASIC language, there was no such thing as declaring a variable with the Dim
statementyou simply created variables on the fly and assigned values to
them. If you wanted to re-use a variable and happened to misspell the name,
the compiler simply took that as an indication that you were declaring a new
variable and barreled happily along. Obviously, this ease-of-use feature leads
to serious debugging issues when your code compiles, but doesn’t work
properly.

Option Explicit forces you to declare your variables, and this is a good thing.
The default setting in Visual Studio .NET is On, and we recommend that you
keep it set this way. It is like having a spell-checker for your variables. You’ll
learn more about what variables are and how to use them later in this chapter.

Option Strict and Type Coercion


Option Strict is a new option and is turned Off by default. The Visual Basic
compiler can often perform automatic type conversions when needed. For

AppDev Sample Chapter--For Review Purposes Only 4-11


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Visual Basic .NET Nuts and Bolts

example, with Option Strict set to Off, the following code declares two
variables and automatically converts the Double value to the Integer value,
resulting in data loss. This is known as type coercion, where the compiler will
simply coerce the fractional Double data type to a whole-number Integer data
type, rounding the extra fractional information:

Dim dbl As Double


Dim int As Integer
dbl = 2.5489
int = dbl
MessageBox.Show(int)

When you set Option Strict to On, the above code won’t even compileyou’d
need to reassure the compiler that data loss was okay by explicitly wrapping
the variable assignment in the CInt conversion function. You’d also need to
explicitly convert the Integer to a String for display in the MessageBox:

int = CInt(dbl)
MessageBox.Show(int.ToString)

This courseware uses the Option Strict = On setting in all of the examples, and
we recommend that you use it in all of your projects as well. Declaring
variables and working with Visual Basic .NET data types are covered in the
next section.

Modules and Classes


To provide some backward compatibility with Visual Basic 6.0, Visual Basic
.NET enables you to create two kinds of code filesclasses and modules.
You’ll learn more about working with classes later in the course, but for now
it’s enough to know that classes can be used to create multiple instances of
objects, all of which are based on the design of the class. Modules, however,
aren’t used for creating objectsthey contain procedures that provide
functionality that your objects can use by calling the procedures.

It is possible to limit the availability, or scope, of the procedures in Modules,


but usually they will have a scope of Public, meaning they can be called from
anywhere, or Friend, meaning that they can be called from anywhere in that
assembly. In Visual Basic .NET each project creates an assembly.

4-12 AppDev Sample Chapter--For Review Purposes Only


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Getting Started with Visual Basic .NET in Visual Studio .NET

TIP: The modules that you create in Visual Basic .NET are really just classes
under the covers. Each of the procedures is defined as a shared method of the
hidden class, providing roughly the same behavior as Visual Basic 6.0
modules. Both modules and classes are saved with a vb file extension, as
shown in Figure 10.

Figure 10. Both modules and classes are saved with a .vb file extension.

AppDev Sample Chapter--For Review Purposes Only 4-13


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Visual Basic .NET Nuts and Bolts

Variables and Data Types


One of the most fundamental building blocks of programming, regardless of
the language, is the variable. And once you start working with variables, you
also need to be aware of data types.

Declaring and Using Local Variables


A variable is a named location in memory that you allocate with the Dim
(short for Dimension) statement. In Visual Basic .NET, a variable can store a
value or refer to an object.

See The following sample code declares a variable named srtTxt within the
btnVariables_Click btnVariables_Click event procedure. The As keyword indicates the data type,
String:

Dim strTxt As String

You then assign a value to strTxt using the equal sign:

strTxt = "Declare Variables"

You can also take care of both the declaration of the variable and the
assignment of the value in one statement:

Dim strTxt2 As String = "Declare Variables 2"

If the declaration and the assignment statement are too long to read on one line
without scrolling, you can use a space and an underscore to indicate that the
same statement continues on the next line:

Dim strTxt3 As String = _


"Declare Variables 3"

4-14 AppDev Sample Chapter--For Review Purposes Only


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Variables and Data Types

NOTE It is important when naming variables to avoid using reserved


words. An extensive list can be found by searching the Help files
for the topic, “Visual Basic Language Keywords.” If you do use a
reserved word, you need to enclose it in square brackets, like this:
[ReservedWord]. In addition, a naming convention is helpful for
documenting and debugging your code. It isn’t really important
which naming convention you usejust that you use it
consistently.

Object Variables
Declaring and instantiating an object variable does not employ different syntax
as it did in Visual Basic 6. Even though object variables don’t actually contain
the objects they point to, the syntax is the same as it is for value-type variables.
You declare the variable as the type of object you want to work with, in this
case a Button control:

Dim btn As Button

Then you point it at an actual button (btnVariables is the name of a button on


the form):

btn = btnVariables

However, btnVariables is already a variable, so creating another variable (btn)


is really redundant in this case.

The following statement assigns the value of the strText String variable to the
Text property of the Button control:

btn.Text = strTxt

The scope of a local variable is the procedure in which it is declaredwhen


the procedure ends, the variable is automatically destroyed. It is accessible
only to code located inside the current procedure, and its contents cannot be
accessed by code executing outside of the procedure. However, not all
variables have local scope and local accessibilityit depends on where and
how they are declared.

AppDev Sample Chapter--For Review Purposes Only 4-15


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Visual Basic .NET Nuts and Bolts

NOTE If you are a Visual Basic 6.0 programmer, one thing you should
make note of is that the Set keyword is no longer used in Visual
Basic .NET. The syntax for object variables is now the same as
that for regular variables.

Variable Scope
Variables are always declared inside of a containerin the previous example,
both local variables are contained in a procedure, which is in turn contained in
a module. If you move the variables outside of the procedure, you can declare
them using the Public or Private keywords:

Public pstrTxt As String


Private mbtn As Button

• Use the Public keyword when you want the variable to be accessible
from anywhere within the same project, from other projects that
reference the project, and from assemblies built from the project. You
can declare a public element in a source file or inside a module, class,
or structure, but not within a procedure.
• Use the Private keyword when you want the variable to be accessible
only from within the same module, class, or structure. You can declare
a private element in a source file or inside a module, class, or
structure, but not within a procedure.
These keywords for determining the scope of variables are referred to as
access modifiers.

NOTE You can also use the Dim keyword interchangeably for Private,
but you should resist the urge to do so. The Private keyword
makes your code easier to read and your intentions clearer. Dim
mainly exists in the language for backwards compatibility with
older versions of the Visual Basic language.

When you create a class module, you also have other options:

• The Protected keyword allows elements to be accessible only from


within the same class, or from a class derived from this class. You can
use Protected only at the class level, not at the procedure level.
• The Friend keyword allows elements to be accessible from within the
same project, but not from outside the project. You can declare Friend
elements in a source file or inside a module, class, or structure, but not
within a procedure.

4-16 AppDev Sample Chapter--For Review Purposes Only


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Variables and Data Types

• Using Protected Friend means that elements are accessible either


from derived classes or from within the same project, or both. You can
use Protected Friend only at the class level.

NOTE Variables declared outside of a procedure in a class are frequently


referred to as fields.

Variable Lifetime
As mentioned earlier, variables declared with the Dim keyword are destroyed
when the procedure terminates. However, you can use the Static keyword if
you want to preserve the value of a variable. Declaring a variable as Static
doesn’t mean it is accessible outside of the procedureit isn’tbut it does
mean that next time around the value will be preserved.

See frmVariables The following example declares a static variable and a regular variable,
increments each one, and displays the results in a label control. The
String.Format method will be discussed later in this chapter.

Static sint As Integer = 0


Dim int As Integer = 0

sint = sint + 1
int = int + 1

If you click the button on the form a few times, the static variable will retain its
value, but each time the regular variable will have the same value since it is
destroyed after the procedure has run, as shown in Figure 11.

Figure 11. Static variables retain their values.

AppDev Sample Chapter--For Review Purposes Only 4-17


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Visual Basic .NET Nuts and Bolts

Block Scope
So far you’ve seen variables with different scope depending on where they are
declared. However, you can narrow the scope of a variable even further by
declaring it inside of a code block. This would include branching and looping
constructions, which will be discussed in detail later in this chapter. The
following example declares a variable inside of a loop. Once the code inside
the loop finishes, the intBlock variable goes out of scope and is inaccessible.

Dim intX As Integer = 1


Do Until intX = 2
Dim intBlock As Integer
intBlock = intX
MessageBox.Show( _
"I'm visible only inside of a block: " _
& intBlock)
intX = intX + 1
Loop

Constants

Constants obey many of the same scoping rules as variables, so you can declare them
in local procedures or have more global scope with the Public and Private keywords.
Where they differ from variables is that constants refer to unchanging constant values.
They are hard-wired on your code, and you cannot change their value at runtime the
way you can with variables. You declare constants in your procedures using Const
keyword (instead of Dim):
Const CompanyName = "MCW Technologies"

You then use constants in your code the same way you would variables:
lbl.Text = CompanyName

.NET Data Types


In the previous section you saw how to declare variables and specify a String
or an Integer data type for those variables. If you are familiar with the data
types used by earlier versions of the Visual Basic language, you may be in for

4-18 AppDev Sample Chapter--For Review Purposes Only


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Variables and Data Types

a surprisedata types in Visual Basic .NET and the Common Language


Runtime are not the same data types you are familiar with. The good news is
that they are the same for all .NET languages, whether you’re programming in
Visual Basic .NET, C#, or COBOL.NET.

Table 1 shows the data types for Visual Basic .NET and the Common
Language Runtime. Each of the listed data types maps to a corresponding
structure in the System namespace, which is shown in the second column.

VB.NET System Data Type Storage Value Range

Boolean System.Boolean 2 bytes True or False.


Byte System.Byte 1 byte 0 through 255 (unsigned).

Char System.Char 2 bytes 0 through 65535 (unsigned).


Date System.DateTime 8 bytes January 1, 0001 to December 31, 9999.
Decimal System.Decimal 16 bytes +/-79,228,162,514,264,337,593,543,950,335 with
no decimal point;
+/-7.9228162514264337593543950335 with 28
places to the right of the decimal;
smallest nonzero number is
+/-0.0000000000000000000000000001.
Double System.Double 8 bytes -1.79769313486231570E+308 to
(double- -4.94065645841246544E-324 for negative values;
precision 4.94065645841246544E-324 to
floating-point) 1.79769313486231570E+308 for positive values.
Integer System.Int32 4 bytes -2,147,483,648 to 2,147,483,647.
Long System.Int64 8 bytes -9,223,372,036,854,775,808 to
(long integer) 9,223,372,036,854,775,807.
Object System.Object (class) 4 bytes Any type can be stored in a variable of type Object.

Short System.Int16 2 bytes -32,768 through 32,767.


Single System.Single 4 bytes -3.4028235E+38 to -1.401298E-45 for negative
(single- values;
precision 1.401298E-45 through 3.4028235E+38 for positive
floating-point) values.
String System.String (class) Depends on 0 to approximately 2 billion Unicode characters.
(variable- implementing
length) platform
Table 1. Visual Basic .NET data types.

AppDev Sample Chapter--For Review Purposes Only 4-19


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Visual Basic .NET Nuts and Bolts

Data Type Notes


Although some of the data types may at first glance look the same as data
types you may have known in Visual Basic 6.0, you need to be aware of some
significant differences:

• The Boolean data type stores only True/False values. Although Visual
Basic .NET represents Boolean values as False = 0 and True = -1, this
is not so in other .NET-aware languages. Make sure to always use the
True and False keywords when working with Booleans.
• An Integer in Visual Basic .NET maps to a Long Integer in Visual
Basic 6.0. A Short in Visual Basic .NET maps to an Integer in Visual
Basic 6.0.
• The Decimal data type has replaced the Visual Basic 6.0 Currency
data type and supports far greater precision and functionality.
• There is no more Variant data type. Although the Object data type
may look like a replacement, it is not the same.
• Unsigned data types are not supported.
• The Char represents a single Unicode character. It allows you to work
with data one character at a time.

System Data Types


The system data types shown in the second column in Table 1 derive from
System.Object. What this means is that you can work with data types as
objects.

See frmDataTypes The code listing in frmDataTypes declares a variable named int as an Integer
data type and a variable named lng as Long:

Dim int As Integer = 30000


Dim lng As Long = 300000

4-20 AppDev Sample Chapter--For Review Purposes Only


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Variables and Data Types

If you type a period after you declare the variable (type int.), you will see
the IntelliSense dialog box shown in Figure 12.

Figure 12. Methods and properties of system value types.

An example of how this is commonly used is the ToString method, which


returns a string representation of the value. You need to use ToString if you
want to display a value in the Text property of a Label controlwith Option
Strict set to On, you’d get a compile error if you tried to set the reference
directly:

Label1.Text = int.ToString

NOTE Every object provides a ToString method, but depending on the


object type, it may not do anything useful. For many classes, it
simply returns the name of the class.

The code in frmDataTypes displays the GetType, ToString, MinValue, and


MaxValue for Integer and Long Integer variables, as shown in Figure 13.

AppDev Sample Chapter--For Review Purposes Only 4-21


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Visual Basic .NET Nuts and Bolts

Figure 13. Displaying GetType, ToString, MinValue, and MaxValue for Integer
and Long Integer Visual Basic .NET data types.

Data Type Conversions


When you set Option Strict, you will need to explicitly convert data types
where there may be data loss. However, you don’t need to if the data type is
being widened or made larger. Table 2 shows the data type mappings where
one data type can be safely converted to another without data loss.

Data Type Widens To

Byte Short, Integer, Long, Decimal, Single, Double


Short Integer, Long, Decimal, Single, Double
Integer Long, Decimal, Single, Double
Long Decimal, Single, Double
Single Double
Date String
Table 2. Data type conversions.

Conversion Functions
Explicitly converting from one data type to another often becomes necessary
when Option Strict is turned on. All of the conversion functions are listed in
Table 3, and follow the general syntax shown here for CBool where the
expression argument is the value to be converted:

4-22 AppDev Sample Chapter--For Review Purposes Only


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Variables and Data Types

CBool(expression)

Function Returns Range for Expression Argument

CBool Boolean Any valid String or numeric expression.


CByte Byte 0 through 255; fractions are rounded.
CChar Char Any valid String expression; value can be 0 through 65535.
CDate Date Any valid representation of a date and time.
CDbl Double -1.79769313486231E+308 through
-4.94065645841247E-324 for negative values;
4.94065645841247E-324 through
1.79769313486231E+308 for positive values.

CDec Decimal +/-79,228,162,514,264,337,593,543,950,335 for zero-scaled


numbers, that is, numbers with no decimal places. For numbers
with 28 decimal places, the range is
+/-7.9228162514264337593543950335. The smallest possible
non-zero number is 0.0000000000000000000000000001.

CInt Integer -2,147,483,648 through 2,147,483,647; fractions are rounded.


CLng Long -9,223,372,036,854,775,808 through 9,223,372,036,854,775,807;
fractions are rounded.
CObj Object Any valid expression.
CShort Short -32,768 through 32,767; fractions are rounded.

CSng Single -3.402823E+38 through -1.401298E-45 for negative values;


1.401298E-45 through 3.402823E+38 for positive values.

CStr String Returns for CStr depend on the expression argument.


Table 3. Conversion functions in Visual Basic .NET.

Note the various ranges for the expression argument in Table 3. If the value
you are trying to convert exceeds the range, you’ll get an overflow error when
converting from one data type to another.

Converting with CType


Another method of converting from one data type to another is to use the
CType function:

CType(expression, typename)

AppDev Sample Chapter--For Review Purposes Only 4-23


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Visual Basic .NET Nuts and Bolts

The expression argument can be any valid expression. The typename


argument can be the name of any data type, object, structure, class, or
interface. An error occurs if the value of the expression argument is outside the
range allowed by the typename argument (see Table 3). For example, you
can’t use CType to convert from Long Integer to an Integeryou need to use
CInt().

See The code in frmConversions shows a couple of the conversion functions and
frmConversions the results, as shown in Figure 14.

Figure 14. Conversion function results.

You can convert a Double to an Integer where the decimal values are
truncated. You can also convert an Integer to a Long Integer, because Longs
are wider than Integers.

Dim dbl As Double = 123456789.7234


Dim int As Integer = CInt(dbl)
Dim str As String = CStr(dbl)

Dim lng As Long = CType(int, Long)

However, you can’t convert a Double to a Short where the non-decimal value
would cause an overflow error, as happens here when the value of dbl is
123,456,789. The maximum value for Short is 32,767.

' Overflow error here!


Dim shrt As Short = CType(dbl, Short)

4-24 AppDev Sample Chapter--For Review Purposes Only


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Variables and Data Types

Operators
Table 4 lists operators commonly used in Visual Basic .NET expressions.

Operator Example Meaning

= Age = 30 True if Age is equal to 30.


<> Age <> 30 True if Age is not equal to 30.
> Age > 30 True if Age is greater than 30.
< Age < 30 True if Age is less than 30.
>= Age >= 30 True if Age is greater than or equal to 30.
<= Age <= 30 True if Age is less than or equal to 30.
^ 3^3 Exponentiation. Result is 27.
+, - 3+3-1 Addition/Subtraction. Result is 5.
*, / 3*3/2 Multiplication/Division. Result is 4.5.
\ 8\3 Integer Division. Result is 2.
& “Hel” & “lo” Concatenation. Result is “Hello”.
And Age = 30 And True if both Age = 30 and Female = True.
Female = True
AndAlso Age = 30 AndAlso If Age is not equal to 30 then MyFunc() never
MyFunc()=5 gets called. All parts of the expression must be
True.
Or Age = 30 Or Female Age is equal to 30 Or Female = True. Returns
= True both Females and Males aged 30.
OrElse Age = 30 OrElse If Age is equal to 30 then MyFunc() never gets
MyFunc()=5 called.
Not Not Female True only if gender isn’t Female. Be careful to
use logical operators with Boolean values only.

Table 4. Equality/comparison/conditional operators.

Although many of the operators used in Visual Basic .NET may be familiar to
users of Visual Basic 6.0, there are also some new operators that are more
directly related to C++. In addition to =, <>, > and <, you also have +=, *=, /=,
\=, &= and -=. These new operators allow you a convenient shorthand when
you want to operate on existing values. AndAlso and OrElse operators let you
short-circuit the And and Or operators, respectively. If the first condition is
true, the second part never gets called.

See frmOperators Figure 15 shows using a few of the operators that work with Integer variables.

AppDev Sample Chapter--For Review Purposes Only 4-25


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Visual Basic .NET Nuts and Bolts

Figure 15. Results of working with operators.

One interesting thing to note is that the last expression uses integer division. If
you attempt to use regular division, you receive an error message. This is
another effect of the Option Strict settingVisual Basic .NET performs an
implicit conversion to the Double data type under the hood when performing
regular division. Even though you’ve declared both variables as Integer, you
still get the error.

' This works


intX \= intY

' This doesn't


intX /= intY

4-26 AppDev Sample Chapter--For Review Purposes Only


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Working with Code

Working with Code


There are two types of procedures you can writefunctions, which return a
value, and sub procedures, which don’t.

Writing Functions and Sub Procedures


To create a function, simply type the scope for your function (either Public or
Private), the word Function, the name of your function, the As keyword, and
the data type. Visual Studio .NET will fill in the End Function statement for
you:

Public Function WhatDayIsIt() As String

End Function

All of the statements in your function need to be written in between the


declaration and the End Function statement. The Return statement indicates
the value you want returned, in this case a String representing the day of the
week for the current date. If you write additional statements after the Return
statement, they will not run, as shown here with MessageBox:

Public Function WhatDayIsIt() As String


Return Now.DayOfWeek.ToString
MessageBox.Show("This code never runs.", _
"After the Return")
End Function

That’s ityou’ve written a very simple function. Most of the functions will be
more complex than this and will consist of multiple statements, but the general
syntax is the same.

A sub procedure has slightly different syntax because it does not return a
result:

Public Sub WhatDaySub()

End Sub

AppDev Sample Chapter--For Review Purposes Only 4-27


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Visual Basic .NET Nuts and Bolts

In this case, the results are written to the Text property of a Label control since
there is no way for the sub procedure to return data by itself:

Public Sub WhatDaySub()


lblResults.Text = Now.DayOfWeek.ToString
End Sub

Executing Procedures

See To call the WhatDayIsIt function and assign the results to a Label control, use
frmProcedures.vb this syntax:

lblResults.Text = WhatDayIsIt()

To execute the WhatDaySub sub procedure, you can simply type the name of
the procedure (don’t forget the empty parentheses):

WhatDaySub()

Passing Arguments
Let’s say you wanted to pass a date to your procedure instead of it being hard-
wired to today’s date. You could pass that value to your function as long as
you declare it when you define your function. Both subs and functions work
with arguments.

NOTE The term argument is often used interchangeably with the term
parameter. The difference between the two is that a parameter is
the definition of what type of value you can pass to a procedure,
and an argument is the actual value that is passed in.

4-28 AppDev Sample Chapter--For Review Purposes Only


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Working with Code

The following example shows the argument dtDate defined as a Date data
type, otherwise the function is the same as the one shown in the previous
example.

Public Function WhatDayParam( _


ByVal dtDate As Date) As String

Return dtDate.DayOfWeek.ToString
End Function

To execute the function, declare a variable as dtDate, assign it a value, and


pass it to the function. In Visual Basic .NET, whenever you assign a literal
date value, you must surround it with the pound sign. If you are assigning a
litteral string value, it must be surrounded by double-quotes.

Dim dt As Date = #3/3/2003#

lblResults.Text = WhatDayParam(dt))

Looping

See All programming languages provide syntax that allows you to iterate through
frmLoopsControl blocks of code until a condition has been met (or while a condition exists).
There are four basic loop types in Visual Basic .NET:

• For…Next
• For Each…Next
• Do…While
• Do…Until

For Loops
A basic For/Next loop uses a variable as a counter, as shown in the following
sample code. The bracketed text indicates optional syntax. For example, if you
leave out the Step 1 instruction, then the statements will repeat three times, or
once for each step, since the default is to only step once. You can change the
step value to another number, or step backwards by supplying a negative
number and stepping from 3 to 1.

AppDev Sample Chapter--For Review Purposes Only 4-29


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Visual Basic .NET Nuts and Bolts

Dim int As Integer


For int = 1 To 3 [Step 1]
' statements repeat 3 times
Next [int]

The bracketed [int] after the Next statement is also optional, but recommended.
It’s conceivable that you may write nested For/Next loops using different
counter variables, and explicitly spell out which one you’re using. This makes
your code more readable.

The For/Each loop shown here lets you traverse the array of characters that
comprise the string “CAT”, one character at a time. The For/Each loop is
capable of walking through any type of collection.

Dim str As String = "CAT"


Dim ch As Char
For Each ch In str
' Walks through the string a character at a time
Next

Do Loops
A For/Next loop lets you loop when you know how many times you want to
loop. A Do loop lets you specify a condition, and depending on how you word
the loop, lets you repeat statements either until a condition is true, or while a
condition is true.

The following example always runs the inside statements at least once until the
condition (int = 3) is True:

Do
int = int + 1
Loop Until int = 3

If you want to check the condition first, and then execute the statements until
the condition is true, write the loop this way:

4-30 AppDev Sample Chapter--For Review Purposes Only


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Working with Code

Do Until int > 3


int = int + 1
Loop

This loop always executes the inside statements at least once, and then
continues while the condition remains True:

Do
int = int + 1
Loop While int < 6

If you want to check the condition first, and then run the inside statements
while the condition remains true, then write the loop this way:

Do While int <= 9


int = int + 1
Loop

NOTE If you need to, you can supply conditional logic and an Exit Do
statement to exit a loop prematurely as part of a condition.

A new variation of the While loop in Visual Basic .NET is While/End While.

While int < 10


int = int + 1
End While

NOTE The While/Wend syntax found in earlier versions of the Basic


programming language has finally become extinct.

Control Flow
You’re probably already familiar with control flow statements from other
programming languages. Visual Basic .NET doesn’t have much in the way of

AppDev Sample Chapter--For Review Purposes Only 4-31


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Visual Basic .NET Nuts and Bolts

surprises herethese will look very familiar, no matter what your


programming background.

The If Statement
The If statement tests for a condition, and if the condition is True, any
statements following the Then statement are executed. If there is only one
statement, you can write it on one line:

If strDay = "Monday" Then lblResults.Text = strDay

However, chances are that you are going to need to add something to the If
statement later. So you’re better off doing a little more typing at the outset and
writing it on three lines, terminating with an End If statement:

If strDay = "Monday" Then


lblResults.Text = strDay
End If

If you want to execute some other statements if the condition is False, you can
add an Else statement:

If strDay = "Monday" Then


' Do Monday stuff
Else
' Do stuff other than Monday stuff
End If

You can add additional conditions with the ElseIf statement:

If strDay = "Monday" Then


' Do Monday stuff
ElseIf strDay = "Tuesday" Then
' Do Tuesday
Else
' Do stuff other than Monday or Tuesday stuff
End If

4-32 AppDev Sample Chapter--For Review Purposes Only


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Working with Code

You can add as many additional ElseIf conditions as you like. However, in
some cases your code may be more readable if you replace the multiple ElseIf
conditions with a Select Case statement.

Select Case
The Select Case statement allows you to branch depending on the output of an
expressionyou’re not limited to True/False like you are with the If
statement. The CalcQuartile example takes an argument of a single letter of the
alphabet, and determines which quartile it falls in. The breakdown is A-F (1),
G-L (2), ' M-S (3), and T-Z (4). This example is more complex than you
would need it to be in an attempt to show all the possible ways to use the Case
statement.

AppDev Sample Chapter--For Review Purposes Only 4-33


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Visual Basic .NET Nuts and Bolts

Public Function CalcQuartile( _


ByVal strValue As String) As Integer
' Calculate the quartile of the alphabet for
' the first letter of varValue.

' The breakdown is: A-F (1), G-L (2),


' M-S (3), T-Z (4)

' This example, in an attempt to show all the


' possible ways to use the Case statement, is
' possibly more complex than necessary.
Dim str As New String(CChar(strValue), 1)
Dim intQuartile As Integer = 0

If Asc(str) > 65 Then


Select Case str.ToUpper
Case "A", "B", "C", "D", "E", "F"
intQuartile = 1
Case "G" To "L"
intQuartile = 2
Case Is <= "S"
intQuartile = 3
Case "T" To "Z"
intQuartile = 4
Case Else
intQuartile = 0
End Select
End If
Return intQuartile
End Function

The sample code contains some built-in functions you may not be familiar
with and which will be explained in other chapters. If you want to test the Case
Else statement, pass a tilde (~) as the strValue argument.

4-34 AppDev Sample Chapter--For Review Purposes Only


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Working with Code

Enumerations

See Enumerations allow you to create symbolic names to represent underlying


frmEnumerations numeric values. For example, you might want to create a rating system for
your products. Instead of using numeric values, you’d like to see ratings where
you wouldn’t have to remember whether the value 3 or 4 was the highest
rating. This is the service that enumerations provideyou declare an
enumeration named Rating and specify the associated values:

Enum Rating
Low = 0
SoSo = 1
Medium = 2
Alright = 3
WayCool = 4
End Enum

Enumerations are very powerful in Visual Basic .NETmuch more so than


they were in Visual Basic 6.0. They derive from the System.Enum class,
which defines a number of methods that allow you to interrogate and transform
a given enumeration.

Enumerations are declared outside the scope of a procedure, and if you don’t
supply a value, then the default is to use the Integer data type and start the
numbering at zero. However, you’re not restricted to declaring your
enumerations this wayyou can specify a different data type, as shown in
Figure 16.

Figure 16. Enumerations can be declared as Byte, Integer, Long, or Short.

AppDev Sample Chapter--For Review Purposes Only 4-35


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Visual Basic .NET Nuts and Bolts

You’re also not restricted to using consecutive numbering. Your enumeration


could look like this if you wanted it to (not that this example makes much
senseit’s just to prove that you can do it):

Enum Rating As Byte


Low = 100
SoSo = 85
Medium = 35
Alright = 75
WayCool = 1
End Enum

In addition to coding your own enumerations, you will undoubtedly notice that
Visual Basic .NET uses them all over the place. For example, the Msgbox
function uses enumerations for specifying which button and icons will be
displayed. The syntax is very similar to that for Visual Basic 6.0:

Public Function MsgBox( _


ByVal Prompt As Object, _
Optional ByVal Buttons As MsgBoxStyle = _
MsgBoxStyle.OKOnly, _
Optional ByVal Title As Object = Nothing _
) As MsgBoxResult

The Buttons argument uses an enumeration named MsgBoxStyle, with a


default value of OKOnly. The other enumerations are displayed in the
IntelliSense dialog box, as shown in Figure 17. You can scroll through the list
to see them all.

Figure 17. MsgBoxStyle enumerations.

4-36 AppDev Sample Chapter--For Review Purposes Only


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Working with Code

The following example uses both the custom Rating enumeration and the
MsgBoxStyle enumerations. The code declares a Rating object, and sets it to
the desired enumeration, WayCool. In the MsgBox function, if you want to use
more than one enumeration (an icon plus a button, or anything else), you must
use the Or operator.

Dim rateMe As Rating


rateMe = Rating.WayCool

MsgBox( _
rateMe.ToString, _
MsgBoxStyle.Information Or MsgBoxStyle.OKOnly, _
"Enumerations")

WARNING! The plus sign (+) doesn’t work for combining MsgBoxStyle
enumerations when Option Strict is turned on.

The results are shown in Figure 18.

Figure 18. Displaying enumerations.

AppDev Sample Chapter--For Review Purposes Only 4-37


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Visual Basic .NET Nuts and Bolts

Summary
• The vbc command line compiler lets you compile applications outside
of Visual Studio .NET.
• A console application can be executed from a command prompt.
• You need to configure options in your profile and in the project
properties that control how code behaves.
• You should always set Option Explicit and Option Strict to On.
• Option Strict disables type coercion.
• All form and module objects are classes in .NET.
• Avoid using reserved words when naming variables.
• The Set keyword is no longer used to instantiate object variables.
• Variables declared with the Dim keyword are destroyed when the
procedure terminates.
• Variables declared with the Static keyword retain their value.
• A block variable is destroyed when the block of code in which it was
declared terminates.
• Data types are the same for all .NET languages and different from
those in Visual Basic 6.0.
• The Boolean data type stores only True/False values.
• An Integer in Visual Basic .NET maps to a Long Integer in Visual
Basic 6.0 and a Short in Visual Basic .NET maps to an Integer.
• The Decimal data type has replaced the Visual Basic 6.0 Currency
data type and has an expanded range.
• The Variant data type found in Visual Basic 6.0 has been removed.
• Data types are objects, and have methods and properties.
• Conversion functions are available to convert one data type to another.
• Functions return a value, while sub procedures do not.
• Date values must be surrounded by pound signs (#), and string values
must be surrounded by double-quotes (").
• Looping syntax that allows you to iterate through blocks of code until
a condition has been met or while a condition exists.
• An If statement conditionally executes statements.
• The Select Case statement allows you to branch depending on the
output of an expression.

4-38 AppDev Sample Chapter--For Review Purposes Only


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Working with Code

• Enumerations allow you to create symbolic names to represent


underlying numeric values.

AppDev Sample Chapter--For Review Purposes Only 4-39


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Visual Basic .NET Nuts and Bolts

(Review questions and answers on the following pages.)

4-40 AppDev Sample Chapter--For Review Purposes Only


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Working with Code

Questions
1. What tools do you need to create a console application?

2. Which two settings in a project should always be set to On?

3. What keyword do you use when you want a local variable to retain its
value the next time a procedure is called?

4. What is the difference between functions and sub procedures?

5. What delimiters are required for literal string values in Visual Basic .NET?
Literal date values?

6. What are enumerations?

AppDev Sample Chapter--For Review Purposes Only 4-41


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Visual Basic .NET Nuts and Bolts

Answers
1. What tools do you need to create a console application?
The vbc command-line compiler and a text editor

2. Which two settings in a project should always be set to On?


Option Explicit and Option Strict

3. What keyword do you use when you want a local variable to retain its
value the next time a procedure is called?
Static

4. What is the difference between functions and sub procedures?


Functions return a value and sub procedures do not.

5. What delimiters are required for literal string values in Visual Basic .NET?
Literal date values?
Strings require double-quotes, dates require the pound sign.

6. What are enumerations?


Enumerations allow you to create symbolic names to represent
underlying numeric values.

4-42 AppDev Sample Chapter--For Review Purposes Only


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Working with Code

Lab 4:
Visual Basic .NET
Nuts and Bolts
TIP: Because this lab includes code that you must type in, we’ve tried to make it
simpler for you. You’ll find all the code in NutsBoltsLab.txt, in the same
directory as the sample project. To avoid typing the code, you can copy/paste
it from the text file instead.

AppDev Sample Chapter--For Review Purposes Only 4-43


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Lab 4:
Visual Basic .NET Nuts and Bolts

Lab 4 Overview
In this lab you’ll learn how to create a simple console application and how to
create a simple form application while working with variables, data types, and
procedures.

To complete this lab, you’ll need to work through two exercises:

• Create a Simple Console Application


• Create a Simple Form Application
Each exercise includes an “Objective” section that describes the purpose of the
exercise. You are encouraged to try to complete the exercise from the
information given in the Objective section. If you require more information to
complete the exercise, the Objective section is followed by detailed step-by-
step instructions.

4-44 AppDev Sample Chapter--For Review Purposes Only


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Create a Simple Console Application

Create a Simple Console Application

Objective
In this exercise, you’ll configure the command line compiler (vbc.exe) so that
it works on your computer. You will then use Notepad to create a simple
application that returns the current date and time. You will compile the
application and execute it from the command prompt.

Things to Consider
• What Visual Basic .NET function returns the current date and time?
• How do you compile a command line application?
• How do you execute your compiled application?

Step-by-Step Instructions
1. Open a Command Prompt window by choosing Programs|Microsoft
Visual Studio .NET|Visual Studio .NET Tools|Visual Studio .NET
Command Prompt from the Windows Start menu.

2. From the Command Prompt window, type:

vbc

and press Enter. You will see all of the possible compiler options, as
shown in Figure 19.

AppDev Sample Chapter--For Review Purposes Only 4-45


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Lab 4:
Visual Basic .NET Nuts and Bolts

Figure 19. The vbc compiler options.

3. To create your application, launch a copy of Notepad from the Windows


Start menu.

4. Type the following code:

' Returns Date and Time


Module DateTimeReturn
Public Sub Main
Dim dt As System.DateTime
dt = Microsoft.VisualBasic.DateAndTime.Now()
System.Console.WriteLine(dt.ToString)
End Sub
End Module

Note that in order to use a DateTime variable and the Now() function, you
must fully-qualify them in order for the compiler to be able to compile
them.

5. Save the file as:

c:\DateTimeReturn.vb

6. To compile the file, type the following statement in the Command


window:

vbc c:\DateTimeReturn.vb

4-46 AppDev Sample Chapter--For Review Purposes Only


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Create a Simple Console Application

This compiles the application and creates the executable.

7. Launch the application by typing DateTimeReturn in the Command


Prompt window. Figure 20 shows the command prompts for compiling
and executing the application.

Figure 20. Compiling and executing the application.

8. To clean up and remove the clutter from your root drive, open an Explorer
window and delete the following files:
c:\DateTimeReturn.vb
c:\DateTimeReturn.exe

AppDev Sample Chapter--For Review Purposes Only 4-47


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Lab 4:
Visual Basic .NET Nuts and Bolts

Create a Simple Form Application

Objective
In this exercise, you’ll create a constant for your company name that will be
available to any procedure in frmMain. You’ll write a procedure to calculate
the weekday of a day in the future. The number of days in the future is passed
as an argument to the function. The function returns the day name in a string.
You will display the day returned in a label control on frmMain. You’ll call the
function and test it to make sure that the value being passed to it is numeric. If
it isn’t, you’ll display a message box informing the user to enter a number.
You’ll set the focus to the text box so the user can enter a number.

Things to Consider
• What keyword do you use to declare a constant that is visible to all
procedures in a form?
• How do you declare a function that takes an input parameter of a
number and returns a string?
• How do you call the function and ensure that a numeric value is being
passed?
• How do you display a constant in a MsgBox?

Step-by-Step Instructions
1. Declare a constant outside of any procedure listings with your company
name, replacing “My Company” with any company name of your
choosing. The constant should be available to any procedure in frmMain:

Public Class frmMain


Inherits System.Windows.Forms.Form

Private Const Company As String = "My Company"

4-48 AppDev Sample Chapter--For Review Purposes Only


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Create a Simple Form Application

2. Create the following function shell by typing the following statement in


frmMain:

Private Function CalculateDay( _


intDays As Integer) As String

and press the Enter key to create a new procedure shell.

3. Declare a variable named dtFuture with the Date data type:

Dim dtFuture As Date

4. Set dtFuture variable to use the DateAdd function to find the date the
specified number of days in the future:

dtFuture = DateAdd(DateInterval.Day, intDays, Now)

5. Return the value of the DayOfWeek method in a string:

Return dtFuture.DayOfWeek.ToString

The completed procedure should look like the following:

Private Function CalculateDay( _


ByVal intDays As Integer) As String
Dim dtFuture As Date
dtFuture = DateAdd(DateInterval.Day, intDays, Now)
Return dtFuture.DayOfWeek.ToString
End Function

6. In the btnGo_Click event handler, declare a String variable named


strReturn to pass to the CalculateDay procedure:

Dim strReturn As String

AppDev Sample Chapter--For Review Purposes Only 4-49


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Lab 4:
Visual Basic .NET Nuts and Bolts
7. Write an If statement to test to see if the value of txtNumDays.Text
TextBox is numeric using the IsNumeric function. If it is, use strReturn to
call CalculateDay, wrapping the string value returned by txtNumDays.Text
in the CInt() function. Display the results in lblResults.Text:

If IsNumeric(txtNumDays.Text) Then
strReturn = CalculateDay(CInt(txtNumDays.Text))
lblResults.Text = strReturn

8. The Else part of the If statement displays a MsgBox for the user to enter a
valid number. Use the Exclamation and OKOnly enumerations for the
buttons. Use the Constant you defined in Step 1 in the Title for the
Msgbox. Clear the lblResults Label control and the txtNumDays TextBox
control by setting their Text property to String.Empty. Set the focus to the
txtNumDays control and close the If construct with an End If:

Else
MsgBox("Please enter a valid number", _
MsgBoxStyle.Exclamation Or MsgBoxStyle.OKOnly, _
Company)
lblResults.Text = String.Empty
txtNumDays.Text = String.Empty
txtNumDays.Focus()
End If

4-50 AppDev Sample Chapter--For Review Purposes Only


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Create a Simple Form Application

9. The entire procedure listing should look like the following:

Private Sub btnGo_Click( _


ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles btnGo.Click

Dim strReturn As String

If IsNumeric(txtNumDays.Text) Then
strReturn = CalculateDay(CInt(txtNumDays.Text))
lblResults.Text = strReturn
Else
MsgBox("Please enter a valid number", _
MsgBoxStyle.Exclamation Or MsgBoxStyle.OKOnly, _
Company)
lblResults.Text = String.Empty
txtNumDays.Text = String.Empty
txtNumDays.Focus()
End If
End Sub

10. Test the procedure by typing a numeric value in the text box and clicking
the Go button. The results should look like those shown in Figure 21.

Figure 21. Twelve days from today is Sunday.

AppDev Sample Chapter--For Review Purposes Only 4-51


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.
Lab 4:
Visual Basic .NET Nuts and Bolts
11. Test the procedure again and type a non-numeric value. The results should
look like those shown in Figure 22.

Figure 22. This is what you see when you don’t enter a numeric value.

4-52 AppDev Sample Chapter--For Review Purposes Only


Copyright © by Application Developers Training Company and AppDev Products Company, LLC
All rights reserved. Reproduction is strictly prohibited.

You might also like