BUY THIS BOOK
Add to Cart

Print Book $14.95


Safari Books Online

What is this?

Add to UK Cart

Print Book £9.95

What is this?

Looking to Reprint this content?


Visual Basic 2005 Jumpstart
Visual Basic 2005 Jumpstart

By Wei-Meng Lee
Price: $14.95 USD
£9.95 GBP

Cover | Table of Contents | Colophon


Table of Contents

Chapter 1: Introducing Visual Basic 2005
When Microsoft released its new version of Visual Basic in 2002, many developers willingly upgraded to take advantage of the new web functionality, security, and performance provided by the .NET platform on which it was built. But in doing so, many also felt they were leaving behind the features that had made Visual Basic 6.0 such a popular tool for the rapid development of Windows applications in the first place.
The release of Visual Basic 2005 (VB 2005) is in many ways a return to Visual Basic's roots as the Rapid Application Development (RAD) tool of choice. Many of the most popular features of earlier versions are back, such as Edit and Continue, along with dozens of new controls, better IntelliSense, an improved debugger, and a host of other tools that speed up programming, debugging, testing, and deployment.
Besides the many tools added to its interactive development environment (IDE), Visual Basic 2005 provides more support than ever for developing the next generation of network-enabled Windows clients and web applications, while a new set of functionality unique to VB 2005—the My namespace—gives you the means by which to perform many common tasks without having to work your way through the complex types of the .NET class libraries.
The best way to learn about Visual Studio 2005 is by using the tool to build an application. In the following sections, you'll assemble a straightforward Windows client that enables users to connect to a database and browse or update the information they find there. You'll work with the authors table of the pub's database that ships with SQL Server 2005. You'll also see how you can extend the application using some of the features new to VB 2005, such as project templates and application configuration tools. Figure 1-1 shows how the main window of the the completed application will look when you've finished your work.
Although this book uses Microsoft Visual Studio 2005 as the tool to build the sample applications, you can also use Microsoft Visual Basic 2005 Express Edition.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Create the Application and Its Main Window
Let's start by using Visual Studio 2005 to create a Windows application, one that you can program with VB 2005.
  1. First, you need to fire up Visual Studio 2005 and open a new project by selecting File New Project… on the Visual Studio 2005 menu. Visual Studio displays the New Project dialog shown in Figure 1-2.
  2. In the Project types window of the New Project dialog, select Visual Basic and then select the Windows Application template in the Visual Studio installed templates dialog window. Keep the default project Name, WindowsApplication1, provided by Visual Studio. Click OK.
    Visual Studio 2005 will present you with its familiar Windows development environment, shown in Figure 1-3, including a designer surface for Form1, which will become the startup window of your application.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Add a Menu and Toolbar
Let's now add a menu and toolbar to the form. In VB 2005, you can create professional looking Windows applications, complete with menus and toolbars that look like those used with Microsoft Office applications.
Figure 1-2: Creating a new Windows application
Figure 1-3: The development environment of Visual Studio 2005
  1. In the Menus & Toolbars tab in Toolbox, shown in Figure 1-4, locate and then drag and drop the ToolStripContainer control onto the form. The ToolStripContainer control allows other controls (such as the ToolStrip control) to anchor in the four positions available (left, right, top, and bottom).
    Figure 1-4: The various controls under the Menus & Toolbars tab in Toolbox
    In the ToolStripContainer Tasks menu, click on the "Dock Fill in Form" link (see Figure 1-5) to dock the ToolStripContainer control onto the form. This will cause the ToolStripContainer control to fill up the entire form and automatically resize itself when the form is resized.
    Figure 1-5: Filling the entire form with the ToolStripContainer control
  2. Now you'll add the application menu. Double-click on the MenuStrip control in the Toolbox to add it to the form. The MenuStrip control displays a standard list of drop-down menus at the top of a window. In the MenuStrip Tasks menu, click on the Insert Standard Items link to add a list of commonly used menu items to the control (see Figure 1-6).
    Your form should now look like the one shown in Figure 1-7.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Connect to a Database and Browse Records
One great time-saving feature in VB 2005 is its new support for automatic data binding. The automatic–data binding feature allows you to connect to a data source and then drag and drop the connection onto a Windows Forms application. A set of controls bound to the data source will then be automatically added to the form, and you can perform a variety of operations on the data source, such as navigating through records, searching for a specific record, and more, without having to write any code.
To see how automatic data binding works, you will now connect to a database and then drag and drop one of its tables onto your form so that you can view and work with its records. You will use SQL Server 2005 Express and the pubs database and then view and edit the records in the authors table.
  1. Select Data Show Data Sources to display the Data Sources window, as shown in Figure 1-10. The Data Sources window allows you to connect to your data sources (such as databases, web services, and business objects) and view their content. Click on the Add New Data Source… link to add a new data source to your project (see Figure 1-10).
    When the Data Source Configuration Wizard appears, click Next.
  2. The Choose a Data Source dialog, which appears next, lets you choose between a database, a web service, or some other object as the source of your data. You'll be using a database, so click the Database icon and then click Next.
  3. Now you need to select a data connection to use to connect to your database. In the "Choose your data connection" dialog, click New Connection….
    Figure 1-10: The Data Sources window
  4. The Add Connection dialog will be shown (see Figure 1-11).
    For this step, I am assuming you have SQL Server 2005 Express installed on your computer. You can download SQL Server 2005 Express from:
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Create an Exit Dialog Box
For most Windows applications, it is customary to ask users if they really want to quit an application when they either click the Close window button or select Exit on the File menu. In this section, you'll use Visual Studio 2005 and VB 2005 to add a dialog box that asks users to confirm that they really want to quit the application when they select either action.
  1. First, let's create the dialog box by adding a new Dialog to the project. You add a new Dialog to your project by right-clicking on the project name in Solution Explorer, which is WindowsApplication1, and then selecting Add New Item…. In the Add New Item dialog, select Dialog and use the default name of Dialog1.vb as shown in Figure 1-19.
    Figure 1-19: Adding a new Windows Form to the project
  2. Notice that the Dialog window already comes with two buttons: OK (OK_Button) and Cancel (Cancel_Button).
  3. Populate the dialog with the Label control shown in Figure 1-20 by dragging and dropping it from the Toolbox. Also, resize the dialog window.
    Figure 1-20: Populating the dialog window with the Label control
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Handle Exit and Close Events
Now it's time to write some code to link the Exit dialog with the events triggered by users when they attempt to exit or close the application.
  1. First, you'll add code to deal with the Exit menu item when a user selects it. To get started, expand the File menu in Form1 and doubleclick on the Exit menu item (see Figure 1-21) to open the code-behind page shown in Figure 1-22.
    Figure 1-21: Coding the File Exit menu item
    Figure 1-22: The code behind of Form1
    The code-behind page contains all of the code that you write for the application. So far in this chapter, all of the work has been done by Visual Studio, but the code it has generated to support your work with the designer and wizards is hidden and out of sight for now. You'll see how to view this code in Chapter 2.
    When you double-click on the Exit item of the application menu on Form1, Visual Studio deduces that you wish to write code to specify how the exit event will be handled, just as it does in VB 6. Note that the code behind page in this example is named Form1.vb. As you can see in Figure 1-22, Visual Studio has already generated the code to create the event handler. All you need to do is specify what specific actions are to be taken when the event handler is called by placing your cursor on the line below the handler declaration and entering your own code.
  2. Now, code the exit event of the ToolStrip control by entering the code shown in bold in Example 1-2 on the code-behind page.
    Example 1-2. Exit menu item event handler
    Private Sub exitToolStripMenuItem_Click( _
       ByVal sender As System.Object, _
       ByVal e As System.EventArgs) _
       Handles exitToolStripMenuItem.Click
        
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Run and Debug the Application
With the code you have added in the last section, it is now time to test the application. This is a good chance for you to see some of the new enhancements in the new Visual Studio 2005 debugger. For this example, you will set a breakpoint so that you can examine the values of variables at a particular point in the code.
  1. Now set a breakpoint in the application by clicking on the gray bar on the left of the code edit window (see Figure 1-24) and then running the application by pressing F5. You will set the breakpoint so that the program halts when you click on the Close box, allowing you to examine the value of DialogResult returned by the Exit dialog box (Dialog1).
    Figure 1-24: Setting a breakpoint
  2. When the form is loaded, close the form to display the dialog box. Click OK, and the application will stop at the breakpoint you have set. To step through the code one line at a time, press F11 (see Figure 1-25).
    Figure 1-25: Stepping through the code
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Inspect an Object at Runtime
The debugger in Visual Studio 2005 now supports a new feature known as DataTips. Using DataTips, you can examine the values in a complex data type while you are debugging the application, otherwise known as debug time. This is a marked improvement over Visual Studio .NET 2003, where only simple data types can be examined by placing the cursor over a variable name.
Figure 1-26 shows the DataTips display for the FormClosingEventArgs object. To see this result, simply position your cursor over the name of the variable or object that you are interested in while the program is stopped at a breakpoint. Not only can you view the values of variables and objects, you can also edit and change their values during debug time.
Figure 1-26: Using the DataTips in Visual Studio 2005
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Add an About Box
VB 2005 now comes with several new templates that make developing a Windows application easy. Among the new templates are:
Explorer Form
Allows you to build applications similar to Windows Explorer, with a tree-like display on the left pane and a detailed view on the right pane.
About Box
Displays an About window listing detailed information (such as version number, copyright, credits, etc.) about the current application.
Login Form
Creates a standard login window to simplify the task of user authentication.
Splash Screen
Displays a welcome screen when your application is launched.
In this section, you will add an About box to your application using the About Box template. The About box for an application is displayed when a user selects Help About… and contains useful information about the application, including its manufacturer and version number. Much of the information in the About box is available from the application and its configuration files.
  1. First, you need to create an About box form. Right-click on the project name (WindowsApplication1) in Solution Explorer and select Add New Item…. Select the About Box template and accept the default name of AboutBox1.vb provided by Visual Studio 2005. Click Add (see Figure 1-27).
    Figure 1-27: Adding an About box to the project
    The AboutBox1.vb form will be added to your project, and Visual Studio 2005 will display a designer for the feature as shown in Figure 1-28.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Configure the Application
In the application that you have built, you can move and anchor the ToolStrip control as you wish while you are using the application. However, you may have noticed that its position is lost each time you exit the application. This is because you need to manually save its positions each time you exit the application, or else the information will be lost. Fortunately, this can be done easily with the new Application Settings feature in VB 2005. In this section, you'll see how.
Figure 1-34: Displaying the About box
  1. You'll begin by adding code to save the location of the ToolStrip control. Select the ToolStrip control and, in its Properties window, select the PropertyBinding property (under the "(ApplicationSettings)" property; see Figure 1-35). Click the "…" button.
    Figure 1-35: Binding application settings
  2. Locate the Location property (this property determines where the control should be placed) and click the drop-down listbox. Click on the New… link at the bottom and create a new application setting called ToolStripLocation (see Figure 1-36). Be sure to set the scope to User. Click OK. Be sure to set the Location property to the newly created application setting.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Summary
In this chapter, you built a Windows application using VB 2005 and Visual Studio 2005. Though the application is simple, its assembly illustrates several key enhancements to the VB 2005 language and the Visual Studio 2005 development tool. To recap, here are the major features you explored:
  • New controls with Smart Tasks menus
  • New Windows application templates
  • Debugging and restored support for edit-and-continue
  • Improved IntelliSense and improved Code Editor
  • Data Source Configuration Wizard
  • Application Settings
In next chapter, you will learn more about the language syntax of the new VB 2005.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 2: Programming with Visual Basic
The Visual Basic 2005 IDE is a powerful RAD tool, but as you saw in Chapter 1, sooner or later you have to roll up your sleeves and write some code, whether it's to handle a simple button event or perform a complex series of calculations on stored data. In this chapter, you'll take a look at the syntax of the VB 2005 language itself. While VB 2005 is a member in good standing of the .NET family of languages, it retains much of the flavor of its VB 6 lineage. This chapter will get you quickly up to speed with VB 2005 language and along the way will show you how some of its features have changed from those of VB 6.
Table 2-1 lists the data types supported by VB 2005 and their counterparts in VB 6. If the size of a VB 6 type differs from that of its corresponding VB 2005 type, its size in bytes is shown in parentheses. For example, the Currency type (which takes up 8 bytes) in VB 6 is replaced in VB 2005 by the Decimal type. The old Decimal type (which takes up 12 bytes in VB 6), is now 16 bytes. Integer is now 4 bytes, instead of its 2 bytes in VB 6. Likewise, the Long data type is now 8 bytes, instead of its 4 bytes in VB 6.
VB 6 Tip: The venerable VB 6 Variant data type in VB 6 is no longer supported in VB 2005; you should use the Object type instead. Object and the types that derive from it are discussed at greater length in Chapter 3.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Data Types
Table 2-1 lists the data types supported by VB 2005 and their counterparts in VB 6. If the size of a VB 6 type differs from that of its corresponding VB 2005 type, its size in bytes is shown in parentheses. For example, the Currency type (which takes up 8 bytes) in VB 6 is replaced in VB 2005 by the Decimal type. The old Decimal type (which takes up 12 bytes in VB 6), is now 16 bytes. Integer is now 4 bytes, instead of its 2 bytes in VB 6. Likewise, the Long data type is now 8 bytes, instead of its 4 bytes in VB 6.
VB 6 Tip: The venerable VB 6 Variant data type in VB 6 is no longer supported in VB 2005; you should use the Object type instead. Object and the types that derive from it are discussed at greater length in Chapter 3.
Table 2-1: Data types in VB 2005
VB 2005 type
Size (bytes)
VB 6 type (size in bytes)
Boolean
Depends on implementing platform
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Variables
In VB 2005, you declare a variable with the Dim (dimension) keyword and you specify its type using the As keyword:
            Dim num1
     Dim num2 As Integer
The first statement declares num1, by default, to be an Object type. The Object type is the base class of all the classes in the .NET Framework. You can think of the Object type as equivalent to the Variant type in VB 6.
The second statement explicitly declares num2 to be an Integer variable.
The following statements declare num1 as a Short type and then assign a value to it:
	 '---range: -32768 <--> 32767
	 Dim num1 As Short
	 num1 = 32767
You should always specify the data type of a variable, because this assures the variable is strongly typed. Strong typing reduces the likelihood of runtime errors and makes your application much more efficient.
In VB 2005, to ensure that variables are declared with a data type (strongly typed), you should add the Option Strict On statement at the top of your code file. All variables must now be declared with a type.
You'll learn more about the importance of strong typing, also known as early binding, in Chapter 3.
In VB 2005, you must declare all of the variables that you use, although you can work around this restriction and use variables without first declaring them with the Option Explicit Off statement. VB 2005 turns on Option Explicit On by default.
VB 6 Tip: VB 6 turns on Option Explicit Off by default. In both VB 6 and VB 2005, it is advisable for you to turn Option Explicit on, because using variables without first declaring them can easily inject potential bugs into your program.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Constants
While variables are a powerful tool, there are times when you want their values to remain constant. Perhaps your program makes repeated use of the value of pi or the natural logarithm e. A constant is like a variable in that it can store a value; unlike a variable, the value of a constant cannot be changed while the program runs. You declare constants using the Const keyword. The following definition assigns the value 3.14 to a constant whose name is pi and then uses it in calculating the area of a circle:
	           Const pi As Double = 3.14
	Dim radius as Double = 5
	Dim area as Double = pi * radius ^ 2
A constant of this type is sometimes called a symbolic constant, because it uses a word to represent a value. VB 2005 supports two additional kinds of constants: literals (see "Literals") and enumerations, or enums (See "Enumerations").
As in VB 6, a literal, or literal constant, as it is sometimes called, represents a particular value in text. For example, the number 32, as it appears in this sentence, is a literal constant. The value of 32 is always 32. Likewise, a quoted string like "Hello World" is also a literal constant. Literal types include Booleans, integers, floating-point numbers, strings, characters, and dates. Any number that is within the range of Integer types, such as 32, is an Integer type by default.
For example, the following statements assign the literal A to ch1 and ch2, both of which are Char types:
	'---assign the character "A" to ch1 and ch2
	Dim ch1 As Char = "A"c
	Dim ch2 As Char = Chr(65)
	Dim longValue as Long = 100L
To represent the quotation character (") in a string variable, use the quotation character twice in succession, as in the following snippet:
	Dim str As String
	' assigns str to "He said: "VB is so cool!""
	str = "He said: ""VB is so cool!"""
To assign a date and time to a DateTime variable, use the # character:
	Dim timeNow As DateTime
	timeNow = #3/22/2005 10:01:19 AM#
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Strings
As in VB 6, VB 2005 String types are used to represent text and are a good example of a reference type, as you saw in "Variables," earlier in this chapter. Strings in .NET are immutable, which means that once you've assigned a value to a string variable, it cannot be changed. If the value of a string variable is changed, another string object is created during runtime. Consider this example:
	Dim st As String
	st = "Hello"
	st &= " World!"
	MsgBox(st) ' prints "Hello World!"
In the above example, two string objects are involved: one for the initialization and one for the concatenation. This problem gets worse if you are doing concatenation in a loop, like the following:
	Dim i As Integer, str As String = ""
	For i = 0 To 10000
       str &= i.ToString
    Next
A much more efficient way to manipulate strings is to use the StringBuilder class, located in the System.Text namespace:
	Dim i As Integer, str As New _
       System.Text.StringBuilder()
    For i = 0 To 10000
       str.Append(i.ToString)
    Next
The "_" (underscore) character is the continuation character in Visual Basic (all versions). It is used to break a long statement into multiple lines.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Arrays
As in VB 6, a VB 2005 array is a collection of variables in which each variable is identified by an index, like mailboxes on a street or players on a team.
For example, the following declaration defines num1 as an array by adding open and closed parentheses to its name:
	Dim num1() As Integer
Note that this declaration simply declares num1 to be an array; the actual size of the array is not known yet. To get num1 to point to an actual array, use the New keyword:
	num1 = New Integer() {1, 2, 3}
num1 is now an array containing three members of Integer data type with values 1, 2, and 3.
Here are some other possible ways to declare and initialize an array:
	Dim num2(2) As Integer
	num2(0) = 1
	num2(1) = 2
	num2(2) = 3
The size of the array is one plus the number declared, as is the case in VB 6. In the above case, the valid index is from 0 to 2, giving a total of 3 members. Note that the following is not allowed:
	Dim num2(2) As Integer = New Integer
	'---Not allowed since size is
	'   already indicated
You can also combine the declaration together with the initialization:
	Dim num3() As Integer = _
        New Integer() {1, 2, 3}
The following are not allowed:
	Dim num3() As Integer = New Integer()
	'---Not allowed; missing {}

	Dim num3() As Integer = New Integer(3)
	'---Not allowed; missing {}

	Dim num3() As New Integer
	'---Not allowed, arrays cannot use New

	Dim num3() as New Integer() {1,2,3}
	'---Syntax error
Once an array is declared, you can change its size by using the ReDim keyword:
	Dim num4() As Integer() = New Integer() {1, 2, 3}
	ReDim num4(5)
VB 6 Tip: In VB 6, you can only ReDim an array if the array is initially declared as a variable length array, as the following shows:
	' array is fixed length
	Dim num1(3) As Integer
	ReDim num1(5) '---error

	' array is variable length
	Dim num2() As Integer
	ReDim num2(5) '---OK
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Type Conversion
You perform a type conversion when you need to convert or assign values from one type to another. This is also known in some circles as casting. Consider the following code:
	Dim num1 as Short = 25
	Dim num2 as Long
	num2 = num1
In this case, the VB 2005 compiler will automatically perform an implicit conversion from the Short type to the Long type. Since all the values that could be stored by the Short type can fit into a Long type, this conversion is known as a widening conversion and is a safe operation. The reverse of widening is a narrowing conversion, which is a conversion from a data type that has a larger range to one with a lower range. Consider the following:
	Dim num1 As Long = 25
	Dim num2 As Short
	num2 = num1
In this example, num1 may potentially contain a value that will cause an overflow in num2 if the assignment takes place. In VB 2005, you can restrict automatic data type conversion by using the Option Strict statement. By default, in VB 2005, the Option Strict statement is set to Off.
VB 6 Tip: In VB 6, there is no Option Strict statement. Hence, the design decision of VB 2005 was to turn Option Strict Off by default so that VB 6 code can be migrated easily.
If you turn Option Strict On, you will need to perform an explicit conversion (or else the compiler will complain):
    '---if option strict on
	num2 = CShort(num1)
	'--OR--
	num2 = CType(num1, Short)
You should preferably turn Option Strict On, so that any narrowing operations you are doing are flagged. This will allow you to take action to catch potential errors that might result from a narrowing conversion. Note that in VB 6, performing a narrowing conversion will not set off a warning since the Option Strict statement is not supported.
VB 6 Tip: The familiar type conversion functions like CInt, CStr, and CSng
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Operators
VB 2005 supports the various operators shown in Table 2-2.
Table 2-2: Operators supported in VB 2005
Type
Language element
Description
Arithmetic
^
Raises to the power of
Subtraction
*
Multiplication
/
Division
\
Integer Division
Mod
Modulus (remainder)
+
Addition
Assignment
=
Assigns a value to a variable or property
^=
Raises the value of a variable to the power of an expression and assigns the result back to the variable (new in VB 2005)
*=
Multiplies the value of a variable by the value of an expression and assigns the result to the variable (new in VB 2005)
/=
Divides the value of a variable by the value of an expression and assigns the result to the variable (new in VB 2005)
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Statements
As in VB 6, a complete program instruction in VB 2005 is called a statement. Programs consist of sequences of statements. You end each statement with a carriage return.
In VB 2005, spaces, tabs, and carriage returns (newlines) are considered to be "whitespace." Extra whitespace is ignored in VB 2005, as in VB 6, a feature that many consider an endearing (and forgiving) quality of the language.
VB 2005 retains the traditional VB 6 statements for decision making but adds a few new wrinkles of its own. Decision-making statements fall into two categories:
  • If-Then-Else
  • Select-Case

Section 2.8.1.1: If-Then-Else

Just as in VB 6, in VB 2005, you make decisions using the If-Then-Else construct.
	                 If <condition> Then
       <statement(s)>
    Else
       <statement(s)>
    End if 
               
Here is a short example:
	Dim day As Short = 4
	Dim dayofWeek As String
	If day = 1 Then
       dayofWeek = "Monday"
    End If
               
In the preceding code, if day is equal to 1, the string "Monday" is then assigned to the dayofWeek variable. For a one-line statement, you can shorten the above code to:
	If day = 1 Then dayofWeek = "Monday"
However, if you have multiple statements to execute if a condition is met, use of the End If statement is mandatory. VB 2005 lets you pack a block of conditional code into a single line. For example, the following block of code:
	If day = 1 Then
        dayofWeek = "Monday"
        currentTime = Now
    End If
is equivalent to this single line of code:
	If day = 1 Then dayofWeek = "Monday" : currentTime = Now
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Functions and Subroutines
VB 2005 supports both functions and subroutines. Basically, support for functions and subroutines is the same in VB 2005 as it is in VB 6. However, VB 2005 provides you with an additional way to return values in a function by means of the new Return statement. VB 2005 programmers have three choices: they can write their own functions, continue using most of the VB 6 functions they have come to know and love, or tap into the rich functionality of the .NET Framework Class Library through the new My namespace (see "My Namespace," later in this chapter).
A function is a block of code that performs some operations and then returns a value. For example, the following function Area takes in two input parameters, computes the area, and then returns the result:
     Public Function Area(ByVal length As Single, _
                 ByVal breadth As Single) As Single
         Dim result As Single
         result = length * breadth
         Return result
     End Function
            
To invoke a function, you simply call the function name with the required argument(s):
	 Dim areaOfRect As Single = Area(4, 5)
            
VB 6 Tip: In VB 6, only functions require the mandatory use of parentheses around the parameter list. But in VB 2005, all functions or subroutine calls require parentheses around the parameter list (even if the parameter list is empty).
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Error Handling
There are two main types of coding errors that programmers generally have to deal with:
  • Compile-time errors
  • Runtime errors
In VB 2005, the background compiler kicks into action every time you type in a line of code. It dynamically compiles your code and warns you of errors before you actually compile it.
In the former case, the compiler detects a syntax error and the IDE handles the error and calls it to the attention of the programmer so that immediate action can be taken to fix the problem. Runtime errors occur while an application is running. It is this type of error that must (and can) be prevented.
To ensure that an application is as robust and bug free as possible, it is important to anticipate as best you can all of the errors that might occur while your program is running. In VB 2005, error handling has been much improved over VB 6. VB 2005 now supports both structured and unstructured error handling.
VB 6 Tip: In VB 6, error handling was unstructured, performed using the primitive On Error and On Error Resume Next statements. The specific information about an error that occurred can be retrieved from the Err object.
In VB 2005, you can implement structured error handling using the Try… Catch…Finally construct. Basically, you place any code that could possibly trigger a runtime error, such as a disk access, into a Try block. Any errors that happen within the Try block will be caught and serviced by the Catch block(s) that follow. This is where you can take actions to correct the error or clean up any resources that you've allocated. The Finally block is executed whether an error occur in the Try block or not. The Finally block is a good place to perform housekeeping chores such as closing a database or file connection.
Example 2-9 shows how you can use
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
My Namespace
One of the problems faced by VB 6 programmers moving to VB 2005 is figuring out which class in the .NET Framework is the appropriate class to use to solve a particular problem. To simplify the transition, VB 2005 provides the new My namespace, which encapsulates some of the most common functionalities that developers need in their daily work.
VB 6 Tip: Most VB 6 predefined functions are still supported in VB 2005. They are located within the Microsoft. VisualBasic namespace (which is automatically referenced by default in all VB 2005 projects) and so you can continue to use your favorite VB 6 functions without doing anything extra.
The My namespace exposes several areas of functionality, as shown in the IntelliSense pop-up in Figure 2-4.
Figure 2-4: The objects exposed by the My namespace
The aim of the My namespace is to provide direct access to commonly used libraries (in the .NET Framework) like Resources that were previously difficult to access. The intuitive hierarchy of the My namespace provides a mechanism that VB 2005 developers can use to easily navigate the .NET Framework class libraries and locate the classes required to perform a particular task. For example, suppose you want to play an audio file in your application. Which class should you use? Using the My namespace, it is easy to locate the right class to use. As it turns out, the class to use can be found in My.Computer.Audio.Play!
The objects exposed by the My namespace are:
My.Application
Provides properties, methods, and events related to the current application.
My.Computer
Provides properties for manipulating computer components, such as audio, the clock, the keyboard, the filesystem, and so on.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Summary
In this chapter, you have been taken on a whirlwind tour of VB 2005 syntax and seen how it compares with that of VB 6. If you are a VB 6 programmer, you'll be happy to have discovered that much of what you already know is still supported (or enhanced) in VB 2005. The new My namespace is another productive feature that Microsoft has built into the language.
In the next chapter, you will learn how you can use the object-oriented programming support found in VB 2005 to become even more productive than you already are, and you'll learn why object orientation is one of the most important additions to the Visual Basic language.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 3: Putting Object-Oriented Programming to Work
Not all object-oriented programming (OOP) concepts are new to Visual Basic. The language has had support for classes and interface-based programming since Version 4, and, arguab