Microsoft Visual Basic .NET Step by Step Version 2003

Overview

Get on the fast track to professional application development with Visual Basic .NET 2003. This practical, hands-on tutorial expertly guides you through the fundamentals—using step-by-step exercises, code samples, optimization tips, and real-world advice to accelerate your productivity. Work at your own pace, learning core programming skills by selecting just the chapters and lessons you need. Upgrade your Visual Basic 6 applications quickly with the help of “Upgrade Notes” sidebars, a special upgrading index, ...

See more details below
Available through our Marketplace sellers.
Other sellers (Paperback)
  • All (50) from $1.99   
  • New (4) from $9.94   
  • Used (46) from $1.99   
Close
Sort by
Page 1 of 1
Showing All
Note: Marketplace items are not eligible for any BN.com coupons and promotions
$9.94
Seller since 2006

Feedback rating:

(58)

Condition:

New — never opened or used in original packaging.

Like New — packaging may have been opened. A "Like New" item is suitable to give as a gift.

Very Good — may have minor signs of wear on packaging but item works perfectly and has no damage.

Good — item is in good condition but packaging may have signs of shelf wear/aging or torn packaging. All specific defects should be noted in the Comments section associated with each item.

Acceptable — item is in working order but may show signs of wear such as scratches or torn packaging. All specific defects should be noted in the Comments section associated with each item.

Used — An item that has been opened and may show signs of wear. All specific defects should be noted in the Comments section associated with each item.

Refurbished — A used item that has been renewed or updated and verified to be in proper working condition. Not necessarily completed by the original manufacturer.

New
PAPERBACK New 0735619050. New, Unused, Soft-cover Book with minor cover and/or page damage (cut, tear or bend/crease typically). Book may have remainder mark on it. Does NOT ... affect book content! Items ship within 24 hours with FREE tracking. Read more Show Less

Ships from: Foley, AL

Usually ships in 1-2 business days

  • Canadian
  • Standard, 48 States
  • Standard (AK, HI)
  • Express, 48 States
  • Express (AK, HI)
$13.36
Seller since 2008

Feedback rating:

(169)

Condition: New
0735619050 BRAND NEW NEVER USED IN STOCK 125,000+ HAPPY CUSTOMERS SHIP EVERY DAY WITH FREE TRACKING NUMBER

Ships from: fallbrook, CA

Usually ships in 1-2 business days

  • Standard, 48 States
  • Standard (AK, HI)
$50.00
Seller since 2014

Feedback rating:

(162)

Condition: New
Brand new.

Ships from: acton, MA

Usually ships in 1-2 business days

  • Standard, 48 States
  • Standard (AK, HI)
$50.00
Seller since 2014

Feedback rating:

(162)

Condition: New
Brand new.

Ships from: acton, MA

Usually ships in 1-2 business days

  • Standard, 48 States
  • Standard (AK, HI)
Page 1 of 1
Showing All
Close
Sort by
Sending request ...

Overview

Get on the fast track to professional application development with Visual Basic .NET 2003. This practical, hands-on tutorial expertly guides you through the fundamentals—using step-by-step exercises, code samples, optimization tips, and real-world advice to accelerate your productivity. Work at your own pace, learning core programming skills by selecting just the chapters and lessons you need. Upgrade your Visual Basic 6 applications quickly with the help of “Upgrade Notes” sidebars, a special upgrading index, and insights into the enhanced Visual Basic .NET Upgrade Wizard. It’s everything you need to start creating .NET-connected software now!

Discover how to:

  • Create a compelling user interface with Toolbox controls, menus, and dialog boxes
  • Use methods in the .NET Framework 1.1 class libraries
  • Utilize the new debugging tools and structured error handlers to build robust code
  • Manage data in your programs using collections, arrays, and string processing techniques
  • Automate Microsoft Office applications and manage processes
  • Manage Windows Forms and create graphics and animation effects
  • Use inheritance and other new object-oriented programming capabilities
  • Write custom code for printers and dialog boxes for printing
  • Manage Access databases and create custom database applications with Microsoft ADO.NET
  • Display HTML documents using Microsoft Internet Explorer
  • Use Web Forms to build Internet interfaces
  • Deploy Visual Basic .NET applications
  • Port Visual Basic 6 programs to Visual Basic .NET

CD features:

  • Code examples in Visual Basic .NET 2003
  • All the book’s practice files
  • Fully searchable eBook

For customers who purchase an ebook version of this title, instructions for downloading the CD files can be found in the ebook.

Read More Show Less

Editorial Reviews

From Barnes & Noble
The Barnes & Noble Review
Now’s a great time to get started with Microsoft Visual Basic .NET. Microsoft’s just released a new version, Visual Basic .NET 2003. It smooths out some of the rough edges inevitable in any “1.0” release, makes VB.NET significantly easier to use, and allows you to migrate more of your code from VB6 (though not by any means all of it). Since VB.NET 2003 supports the new .NET Framework 1.1, it even provides integrated tools for programming some 200-plus mobile web devices.

No matter where you’re coming from, if you want to learn Visual Basic .NET 2003, you’ll welcome Microsoft Visual Basic .NET 2003 Step by Step.

Michael Halvorson’s crafted this tutorial to offer three specific learning paths: for those new to programming, those upgrading from Visual Basic 6, and those moving from any other version of BASIC.

Beginners and upgraders alike will appreciate the simple hands-on walkthroughs of the Visual Basic/Visual Studio .NET environment; writing your first program; and working with toolbox controls, menus, and dialog boxes.

Beginners will devour the programming fundamentals section. Those moving from Visual Basic 6 or VB.NET “1.0” can skim much of it. But even they should still pay special attention to the extensive upgrade notes, Halvorson’s practical guidance on debugging, and his chapter on error handling, which has been radically revamped in VB.NET.

With the basics in place, you’re on to more serious stuff. You’ll learn how to create standard modules, user-defined functions, and Sub procedures -- essential for any larger or team-based development project. You’ll master arrays (familiar to all experienced programmers) and collections (a feature many programmers haven’t used). There’s a full chapter on string processing and manipulating the contents of text files.

Next, Halvorson shows how to control Microsoft Office XP applications from VB .NET. While Office still relies primarily on VBA, not VB.NET, the forthcoming Office 2003 is expected to add significant new .NET support. Even, now, however -- as Halvorson shows you -- you can incorporate powerful Office functionality in your applications. (Halvorson’s examples, drawing on Excel, include a mortgage payment calculator that uses Excel’s Pmt function.)

In developing .NET, Microsoft’s given significant attention to deployment -- and so does Halvorson. You’ll learn how to add a deployment project to your solution; how to create a setup program for your application; customize your setup program using properties and build settings; and how to test installs and uninstalls.

Next, Halvorson turns to advanced user interface design: Windows Forms techniques; (judiciously) adding graphics and animation effects to your software; inheriting forms using the Inheritance Picker; and working with printers.

You’re likely to find the coverage of printers especially useful. As Halvorson notes, “printing support doesn’t come automatically in Visual Basic .NET.” So he offers plenty of code you can plunk into your applications almost intact. (The accompanying CD-ROM contains this and all the other code in the book.)

You’ll find two full chapters on database programming with ADO.NET and .NET’s powerful DataGrid control, which makes presenting data about as easy as it’s ever been. There’s also a simple introduction to Web development with Web Forms. Halvorson concludes by taking a closer look at migrating your old VB code -- when it makes sense, when to start fresh, and when to leave well enough alone. Bill Camarda

Bill Camarda is a consultant, writer, and web/multimedia content developer. His 15 books include Special Edition Using Word 2000 and Upgrading & Fixing Networks for Dummies, Second Edition.

Read More Show Less

Product Details

  • ISBN-13: 9780735619050
  • Publisher: Microsoft Press
  • Publication date: 3/26/2003
  • Series: Microsoft Step by Step Series
  • Edition description: REV
  • Edition number: 2
  • Pages: 688
  • Product dimensions: 7.34 (w) x 8.86 (h) x 1.76 (d)

Meet the Author

Michael Halvorson is the author or co-author of twenty computer books, including Microsoft Office XP Inside Out, Visual Basic 6 Professional Step By Step, Learn Microsoft Visual Basic 6 Now, Running Microsoft Office 2000 Premium Edition, and Microsoft Word 97/Visual Basic Step by Step. Michael earned a bachelor's degree in Computer Science from Pacific Lutheran University in Tacoma, Washington, and master’s and doctoral degrees in History from the University of Washington in Seattle, Washington. He was employed at Microsoft Corporation as a technical editor, acquisitions editor, and localization manager from 1985 to 1993. Michael currently spends his time developing innovative software solutions for Microsoft Office and Microsoft Visual Basic .NET, and teaching European history courses at colleges in the Pacific Northwest.

Read More Show Less

Table of Contents

Acknowledgments
Introduction
Pt. 1 Getting Started with Microsoft Visual Basic .NET 2003
Ch. 1 Opening and Running a Visual Basic .NET 2003 Program 3
Ch. 2 Writing Your First Program 33
Ch. 3 Working with Toolbox Controls 63
Ch. 4 Working with Menus and Dialog Boxes 95
Pt. 2 Programming Fundamentals
Ch. 5 Visual Basic .NET Variables and Operators 125
Ch. 6 Using Decision Structures 161
Ch. 7 Using Loops and Timers 185
Ch. 8 Debugging Visual Basic .NET Programs 209
Ch. 9 Trapping Errors Using Structured Error Handling 225
Pt. 3 Managing Corporate Data
Ch. 10 Using Modules and Procedures 249
Ch. 11 Using Arrays and Collections to Manage Data 277
Ch. 12 Exploring Text Files and String Processing 307
Ch. 13 Automating Microsoft Office Applications and Managing Processes 341
Ch. 14 Deploying Visual Basic .NET Applications 361
Pt. 4 Advanced User Interface Design
Ch. 15 Managing Windows Forms 393
Ch. 16 Adding Graphics and Animation Effects 421
Ch. 17 Inheriting Forms and Creating Base Classes 439
Ch. 18 Working with Printers 459
Pt. 5 Database Programming
Ch. 19 Getting Started with ADO.NET 487
Ch. 20 Data Presentation Using the DataGrid Control 513
Pt. 6 Internet Programming
Ch. 21 Displaying HTML Documents Using Internet Explorer 531
Ch. 22 Using Web Forms to Build Interactive Web Applications 545
Pt. 7 Appendixes
App. A Upgrading Visual Basic 6 Programs to Visual Basic .NET 2003 573
App. B Where to Go for More Information 587
Upgrading Index 591
Index 597
Read More Show Less

First Chapter

  • The Anatomy of a Visual Basic Program Statement
  • Using Variables to Store Information
    • Setting Aside Space for Variables: The Dim Statement
  • Using Variables in a Program
  • Using a Variable to Store Input
  • Using a Variable for Output
  • Working with Specific Data Types
    • Constants: Variables That Don’t Change
  • Working with Visual Basic Operators
    • Basic Math: The +, –, *, and / Operators
    • Using Advanced Operators: \, Mod, ^, and &
  • Working with Math Methods in the .NET Framework
  • Operator Precedence
  • One Step Further: Using Parentheses in a Formula
  • Lesson 5 Quick Reference

Chapter 5  Visual Basic .NET Variables and Operators
In this chapter, you will learn how to: :
  • Use variables to store data in your programs.
  • Get input by using the InputBox function.
  • Display messages by using the MsgBox function.
  • Work with different data types.
  • Use mathematical operators and functions in formulas.
  • Use the math methods in the System.Math class of the .NET Framework.
  • Use variables and operators

In Part 1, you learned how to create the user interface of a Microsoft Visual Basic .NET program and how to build and run a program in the Microsoft Visual Studio development environment. In the next five chapters, you’ll learn more about Visual Basic program code—the statements and keywords that form the core of a Visual Basic program. After you complete Part 2, you’ll be ready for more advanced topics.

In this chapter, you’ll learn how to use variables to store data temporarily in your program and how to use mathematical operators to perform tasks such as addition and multiplication. You’ll also learn how to use mathematical functions to perform calculations involving numbers, and you’ll use the InputBox and MsgBox functions to gather and present information by using dialog boxes. Finally, you’ll get your first real look at using classes in the .NET Framework to perform useful work in a program.


Upgrade Notes: What’s New in Visual Basic .NET?:
If you’re experienced with Visual Basic 6, you’ll notice some new features in Visual Basic .NET, including the following:
  • To encourage better programming practices and cleaner program code, all Visual Basic .NET variables must be declared before they’re used. The implicit declaration of variables (using variables without declaring them) is allowed only if you use the Option Explicit Off statement—a practice that’s discouraged.
  • Visual Basic no longer supports the Variant data type. You should declare all variables using Dim and the keyword As to identify the type of data that they’ll hold.
  • There are several new fundamental data types, and some of the older data types now support different ranges. For example, there’s a 16-bit Short data type, a 32-bit Integer data type, and a 64-bit Long data type. The Visual Basic 6 Currency data type has been replaced with the Decimal data type.
  • Visual Basic .NET includes a new statement named Option Strict. When Option Strict is turned on, variables usually need to be the same type if they’re added, compared, or combined. (Sometimes variables can be different types, as long as there won’t be any data loss.) This means that type conversion is more important in Visual Basic .NET than in Visual Basic 6, and you’ll need to become familiar with type conversion functions such as CInt, CLng, and CType to make different types of data compatible. As you upgrade your applications, you can use the Option Strict Off statement to continue combining data types as you did in Visual Basic 6 (permitting what’s known as automatic type coercion), but this feature should be used sparingly and not relied on for future versions of Visual Basic .NET.
  • There are now shortcuts for mathematical operations with some arithmetic operators, such as addition (+), subtraction (-), and multiplication (*). These shortcuts allow you to write a formula such as X = X + 2 using the syntax X += 2.
  • Visual Basic .NET no longer provides built-in keywords (such as Abs or Cos) for mathematical operations. Instead, you must use the methods in the System.Math class library of the .NET Framework for mathematical functions. The functionality of these methods is similar to the familiar Visual Basic 6 functions, although a few names have changed (for example, Sqr is now Sqrt).
  • Visual Studio includes a MessageBox object, which is an alternative to the MsgBox function for displaying message boxes. To display a message box, you use the MessageBox.Show method.

The Anatomy of a Visual Basic Program Statement

As you learned in Chapter 2, a line of code in a Visual Basic program is called a program statement. A program statement is any combination of Visual Basic keywords, properties, functions, operators, and symbols that collectively create a valid instruction recognized by the Visual Basic compiler. A complete program statement can be a simple keyword, such as

End

which halts the execution of a Visual Basic program, or it can be a combination of elements, such as the following statement, which uses the TimeString property to assign the current system time to the Text property of the Label1 object:

Label1.Text = TimeString

The rules of construction that must be used when you build a programming statement are called statement syntax. Visual Basic shares many of its syntax rules with earlier versions of the BASIC programming language and with other language compilers. The trick to writing good program statements is learning the syntax of the most useful language elements and then using those elements correctly to process the data in your program. Fortunately, Visual Basic does a lot of the toughest work for you, so the time you spend writing program code will be relatively short, and the results can be used again in future programs.

In the following chapters, you’ll learn the most important Visual Basic keywords and program statements, as well as many of the objects, properties, and methods provided by Visual Studio controls and the .NET Framework. You’ll find that these keywords and objects will complement nicely the programming skills you’ve already learned and will help you write powerful programs in the future. Variables and data types, the first topics, are critical features of nearly every program.

Using Variables to Store Information

A variable is a temporary storage location for data in your program. You can use one or many variables in your code, and they can contain words, numbers, dates, or properties. Variables are useful because they let you assign a short and easy-to-remember name to each piece of data you plan to work with. Variables can hold information entered by the user at runtime, the result of a specific calculation, or a piece of data you want to display on your form. In short, variables are handy containers that you can use to store and track almost any type of information.

Using variables in a Visual Basic .NET program requires some planning. Before you can use a variable, you must set aside memory in the computer for the variable’s use. This process is a little like reserving a seat at the theater or a baseball game. I’ll cover the process of making reservations for, or declaring, a variable in the next section.

Setting Aside Space for Variables: The Dim Statement

In Visual Basic .NET, you must explicitly declare your variables before using them. This is a change from earlier versions of Visual Basic, where (under certain circumstances) you could declare variables implicitly—in other words, simply by using them and without a Dim statement. This was a flexible but rather risky practice—it created the potential for variable confusion and misspelled variable names, which introduced potential bugs into the code that might (or might not) be discovered later.

To declare a variable in Visual Basic .NET, type the variable name after the Dim statement. (Dim stands for dimension.) This declaration reserves room in memory for the variable when the program runs, and it lets Visual Basic know what type of data it should expect to see later. Although this declaration can be done at any place in the program code (as long as the declaration happens before the variable is used), most programmers declare variables in one place at the top of their event procedures or code modules.

For example, the following statement creates space for a variable named LastName in a program that will hold a textual, or string, value:

Dim LastName As String

Note that in addition to identifying the variable by name, I’ve used the As keyword to give the variable a particular type, and I’ve identified the type by using the keyword String. (You’ll learn about other data types later in this chapter.) A string variable contains textual information: words, letters, symbols—even numbers. I find myself using string variables a lot; they hold names, places, lines from a poem, the contents of a file, and many other "wordy" data. Why do you need to declare variables? Visual Basic wants you to identify the name and the type of your variables in advance so that the compiler can set aside the memory the program will need to store and process the information held in variables. Memory management might not seem like a big deal to you (after all, modern personal computers have lots of RAM and gigabytes of free hard disk space), but in some programs, memory usage can be consumed quickly, and it’s a good practice to take memory allocation seriously even as you take your first steps as a programmer. As you’ll soon see, different types of variables have different space requirements and size limitations.


NOTE:
In some earlier versions of Visual Basic, specific variable types (such as String or Integer) weren’t required—information was simply held using a generic (and memory hungry) data type called Variant, which could hold data of any size or format. Variants are no longer supported in Visual Basic .NET. Although they were handy for beginning programmers, the way they were designed made them slow and inefficient, and they allowed variables to be converted from one type to another too easily—causing unexpected results.

After you declare a variable, you’re free to assign information to it in your code by using the assignment operator (=). For example, the following program statement assigns the last name "Jefferson" to the LastName variable:

LastName = "Jefferson"

Note that I was careful to assign a textual value to the LastName variable because it’s of the type String. I could also assign values with spaces, symbols, or numbers to the variable, such as

LastName = "1313 Mockingbird Lane"

but the variable would still be considered a string value. The number portion could only be used in a mathematical formula if it were first converted to an integer or a floating-point value using one of a handful of conversion functions I’ll discuss later in this book.

After the LastName variable is assigned a value, it can be used in place of the name "Jefferson" in your code. For example, the assignment statement

Label1.Text = LastName

would display Jefferson in the first label (Label1) on your form.


NOTE:
If you really want to declare variables "the old way" in Visual Basic .NET, that is, without explicitly declaring them using the Dim statement, you can place the statement Option Explicit Off at the very top of your form or module’s program code (before any event procedures), and it will defeat Visual Basic’s default requirement that variables be declared before they’re used. I don’t recommend this statement as a permanent addition to your code, but you might find it useful temporarily as you convert older Visual Basic programs to Visual Studio .NET.

Using Variables in a Program

Variables can maintain the same value throughout a program, or they can change values several times, depending on your needs. The following exercise demonstrates how a variable named LastName can contain different text values and how the variable can be assigned to object properties.


Change the value of a variable:
  1. Start Visual Studio.
  2. On the File menu, point to Open, and then click Project.
  3. The Open Project dialog box appears.

  4. Open the Variable Test project in the c:\vbnet03sbs\chap05\variable test folder.
  5. If the project’s form isn’t visible, click Form1.vb in Solution Explorer, and then click the View Designer button.
  6. The Variable Test form appears in the Windows Forms Designer. Variable Test is a skeleton program—it contains a form with labels and buttons for displaying output, but little program code. You’ll add code in this exercise.

    The Variable Test form looks like this:

    (Image unavailable)

    The form contains two labels and two buttons. You’ll use variables to display information in each of the labels.


    NOTE:
    The label objects look like boxes because I set their BorderStyle properties to Fixed3D.
  7. Double-click the Show button.
  8. The Button1_Click event procedure appears in the Code Editor.

  9. Type the following program statements to declare and use the LastName variable:
  10. Dim LastName As String
     
    LastName = "Luther"
    Label1.Text = LastName
     
    LastName = "Bodenstein von Karlstadt"
    Label2.Text = LastName

    The program statements are arranged in three groups. The first statement declares the LastName variable by using the Dim statement and the String type. The second and third lines assign the name "Luther" to the LastName variable and then display this name in the first label on the form. This example demonstrates one of the most common uses of variables in a program—transferring information to a property.

    The fourth line assigns the name "Bodenstein von Karlstadt" to the LastName variable (in other words, it changes the contents of the variable). Notice that the second string is longer than the first and contains a few blank spaces. When you assign text strings to variables, or use them in other places, you need to enclose the text within quotation marks. (You don’t need to do this with numbers.)

    Finally, keep in mind another important characteristic of the variables being declared in this event procedure—they maintain their scope, or hold their value, only within the event procedure you’re using them in. Later in this chapter, you’ll learn how to declare variables so that they can be used in any of your form’s event procedures.

  11. Click the Form1.vb [Design] tab to display the form again.
  12. Double-click the Quit button.
  13. The Button2_Click event procedure appears in the Code Editor.

  14. Type the following program statement to stop the program:
  15. End

    Your screen should look like this:

    (Image unavailable)

  16. Click the Save All button to save your changes.
  17. Click the Start button on the Standard toolbar to run the program.
  18. The program runs in the development environment.

  19. Click the Show button.
  20. The program declares the variable, assigns two values to it, and copies each value to the appropriate label on the form. The program produces the following output:

    (Image unavailable)

  21. Click the Quit button to stop the program.
  22. The program stops, and the development environment returns.


Variable Naming Conventions:
Naming variables can be a little tricky because you need to use names that are short but intuitive and easy to remember. To avoid confusion, use the following conventions when naming variables:

Begin each variable name with a letter. With the exception of the underscore, this is a Visual Basic requirement. Variable names can contain only letters, numbers, and underscores.

Although variable names can be virtually any length, try to keep them under 33 characters to make them easier to read. (Variable names were limited to 255 characters in Visual Basic 6, but that’s no longer a constraint.)

Make your variable names descriptive by combining one or more words when it makes sense to do so. For example, the variable name SalesTaxRate is much clearer than Tax or Rate.

Use a combination of uppercase and lowercase characters and numbers if you want. An accepted convention is to capitalize the first letter of each word in a variable; for example, DateOfBirth. However, some programmers prefer to use so-called camel casing (making the first letter of a variable name lowercase) to distinguish variable names from functions and module names (which usually do begin with uppercase letters). Examples of camel casing include dateOfBirth, employeeName, and counter.

Don’t use Visual Basic keywords, objects, or properties as variable names. If you do, you’ll get an error when you try to run your program.

(Optional) Begin each variable name with a two- or three-character abbreviation corresponding to the type of data that’s stored in the variable. For example, use strName to show that the Name variable contains string data. Although you don’t need to worry too much about this detail now, you should make a note of this convention for later—you’ll see it in the Visual Studio online Help and in many of the advanced books about Visual Basic programming. (This convention and abbreviation scheme was originally created by Microsoft Distinguished Engineer Charles Simonyi and is sometimes called the Hungarian Naming Convention.)


Using a Variable to Store Input

One practical use for a variable is to hold information input from the user. Although you can often use an object such as a list box or a text box to retrieve this information, at times you might want to deal directly with the user and save the input in a variable rather than in a property. One way to retrieve input is to use the InputBox function to display a dialog box on the screen, and then use a variable to store the text the user types. You’ll try this approach in the following example.

Get input by using InputBox

  1. On the File menu, point to Open, and then click Project.
  2. The Open Project dialog box appears.

  3. Open the Input Box project in the c:\vbnet03sbs\chap05\input box folder.
  4. The Input Box project opens in the development environment. Input Box is a skeleton program.

  5. If the project’s form isn’t visible, click Form1.vb in Solution Explorer, and then click the View Designer button.
  6. The form contains one label and two buttons. You’ll use the InputBox function to get input from the user, and then you’ll display the input in the label on the form.

  7. Double-click the Input Box button.
  8. The Button1_Click event procedure appears in the Code Editor.

  9. Type the following program statements to declare two variables and call the InputBox function:
  10. Dim Prompt, FullName As String
    Prompt = "Please enter your name."
     
    FullName = InputBox(Prompt)
    Label1.Text = FullName

    This time, you’re declaring two variables by using the Dim statement: Prompt and FullName. Both variables are declared using the String type. (You can declare as many variables as you want on the same line, as long as they’re of the same type.) Note that in Visual Basic 6, this same syntax would have produced different results. Dim would create the Prompt variable using the Variant type (because no type was specified), and Dim would create the FullName variable using the String type. But this logical inconsistency has been fixed in Visual Basic .NET.

    The second line in the event procedure assigns a text string to the Prompt variable. This message will be used as a text argument for the InputBox function. (An argument is a value or an expression passed to a procedure or a function.) The next line calls the InputBox function and assigns the result of the call (the text string the user enters) to the FullName variable. InputBox is a special Visual Basic function that displays a dialog box on the screen and prompts the user for input. In addition to a prompt string, the InputBox function supports other arguments you might want to use occasionally. Consult the Visual Basic online Help for details.

    After InputBox has returned a text string to the program, the fourth statement in the procedure places the user’s name in the Text property of the Label1 object, which displays it on the form.


    NOTE:
    In older versions of BASIC, the InputBox function was spelled with a $ character at the end to help programmers remember that the function returned information in the string ($) data type. String variables were also identified with the $ symbol on occasion. These days we don’t use type character abbreviations. String ($), Integer (%), and the other type abbreviations are relics.
  11. Save your changes.
  12. Do you remember which toolbar button to click to save your project? See step 10 of the previous exercise if you’ve forgotten.

  13. Click the Start button on the Standard toolbar to run the program.
  14. The program runs in the development environment.

  15. Click the Input Box button.
  16. Visual Basic executes the Button1_Click event procedure, and the Input Box dialog box appears on your screen, as shown here:

    (Image unavailable)

  17. Type your full name, and then click OK.
  18. The InputBox function returns your name to the program and places it in the FullName variable. The program then uses the variable to display your name on the form, as shown here:

    (Image unavailable)

    Use the InputBox function in your programs anytime you want to prompt the user for information. You can use this function in combination with the other input controls to regulate the flow of data into and out of a program. In the next exercise, you’ll learn how to use a similar function to display text in a dialog box.

  19. Click the Quit button on the form to stop the program.
  20. The program stops, and the development environment returns.


What Is a Function?:
InputBox is a special Visual Basic keyword known as a function. A function is a statement that performs meaningful work (such as prompting the user for information or calculating an equation) and then returns a result to the program. The value returned by a function can be assigned to a variable, as it was in the Input Box program, or it can be assigned to a property or another statement or function. Visual Basic functions often use one or more arguments to define their activities. For example, the InputBox function you just executed used the Prompt variable to display dialog box instructions for the user. When a function uses more than one argument, commas separate the arguments, and the whole group of arguments is enclosed in parentheses. The following statement shows a function call that has two arguments:

FullName = InputBox(Prompt, Title)


Using a Variable for Output

You can display the contents of a variable by assigning the variable to a property (such as the Text property of a label object) or by passing the variable as an argument to a dialog box function. One useful dialog box function for displaying output is the MsgBox function. When you call the MsgBox function, it displays a dialog box, sometimes called a message box, with various options that you can specify. Like InputBox, it takes one or more arguments as input, and the results of the function call can be assigned to a variable. The syntax for the MsgBox function is

ButtonClicked = MsgBox(PromptButtonsTitle)

where Prompt is the text to be displayed in the message box, Buttons is a number that specifies the buttons, icons, and other options to display for the message box, and Title is the text displayed in the message box title bar. The variable ButtonClicked is assigned the result returned by the function, which indicates which button the user clicked in the dialog box.

If you’re just displaying a message using the MsgBox function, the ButtonClicked variable, the assignment operator (=), the Buttons argument, and the Title argument are optional. You’ll be using the Title argument, but you won’t be using the others in the following exercise; for more information about them (including the different buttons you can include in MsgBox and a few more options), search for MsgBox in Visual Basic online Help.


NOTE:
Visual Basic .NET provides both the MsgBox function and the MessageBox class for displaying text on a form using a dialog box. The MessageBox class is part of the System.Windows.Forms namespace, takes arguments much like MsgBox, and is displayed using the Show method. I’ll use both MsgBox and MessageBox in this book.

Now you’ll add a MsgBox function to the Input Box program to display the name the user enters in the Input Box dialog box.


Display a message by using MsgBox:
  1. If the Code Editor isn’t visible, double-click the Input Box button on the Input Box form.
  2. The Button1_Click event procedure appears in the Code Editor. (This is the code you entered in the last exercise.)

  3. Select the following statement in the event procedure (the last line):
  4. Label1.Text = FullName

    This is the statement that displays the contents of the FullName variable in the label.

  5. Press the Delete key to delete the line.
  6. The statement is removed from the Code Editor.

  7. Type the following line into the event procedure as a replacement:
  8. MsgBox(FullName, , "Input Results")

    This new statement will call the MsgBox function, display the contents of the FullName variable in the dialog box, and place the words Input Results in the title bar. (The optional Buttons argument and the ButtonClicked variable are irrelevant here and have been omitted.) Your event procedure should look like this:

    (Image unavailable)

  9. Click the Start button on the Standard toolbar.
  10. Click the Input Box button, type your name in the input box, and then click OK.
  11. Visual Basic stores the input in the program in the FullName variable and then displays it in a message box. Your screen should look similar to this:

    (Image unavailable)

  12. Click OK to close the message box. Then click Quit to close the program.
  13. The program closes, and the development environment returns.


    NOTE:
    You might have noticed that when you run a Visual Basic program, Visual Studio .NET automatically saves your project before it starts the compiler and displays your opening form. This is a safety feature that should prevent data loss if something unexpected were to happen during the compilation.

Working with Specific Data Types

The String data type is useful for managing text in your programs, but what about numbers, dates, and other types of information? To allow for the efficient memory management of all types of data, Visual Basic provides several additional data types that you can use for your variables. Many of these are familiar data types from earlier versions of BASIC or Visual Basic, and some of the data types are new or have been changed in Visual Studio .NET to allow for the efficient processing of data in newer 64-bit computers.

The following table lists the fundamental (or elementary) data types in Visual Basic .NET. You’ll gain a performance advantage in your programs if you choose the right data type for your variables—a size that’s neither too big nor too small. In the next exercise, you’ll see how several of these data types work.


NOTE:
Variable storage size is measured in bits. The amount of space required to store one standard (ASCII) keyboard character in memory is 8 bits, which equals 1 byte.
Data type Size Range Sample usage
Short 16-bit –32,768 through 32,767 Dim Birds As Short 
Birds = 12500
Integer 32-bit –2,147,483,648 through 2,147,483,647 Dim Insects As Integer
Insects = 37500000
Long 64-bit –9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 Dim WorldPop As Long 
WorldPop = 4800000004
Single 32-bit floating point –3.4028235E38 through 3.4028235E38 Dim Price As Single 
Price = 899.99
Double 64-bit floating point –1.79769313486231E308 through 1.79769313486231E308 Dim Pi As Double
Decimal 128-bit values up to +/–79,228 × 1024 Dim Debt As Decimal
Debt = 7600300.50
Byte 8-bit 0–255 (no negative numbers) Dim RetKey As Byte
RetKey = 13
Char 16-bit Any Unicode symbol in the range 0–65,535 Dim UnicodeChar As Char
UnicodeChar = "Ä"
String Usually 16-bits per character 0 to approximately 2 billion 16-bit Unicode characters Dim Dog As String
Dog = "pointer"
Boolean 16-bit True or False (during conversions, 0 is converted to False, other values to True) Dim Flag as Boolean
Flag = True
Date 64-bit January 1, 0001, through December 31, 9999 Dim Birthday as Date
Birthday = #3/1/1963#
Object 32-bit Any type can be stored in a
variable of type Object
Dim MyApp As Object
MyApp = CreateObject _
  ("Word.Application")

Use fundamental data types in code:
  1. On the File menu, point to Open, and then click Project.
  2. The Open Project dialog box appears.

  3. Open the Data Types project in the c:\vbnet03sbs\chap05\data types folder.
  4. If the project’s form isn’t visible, click Form1.vb in Solution Explorer, and then click the View Designer button.
  5. Data Types is a complete Visual Basic program that demonstrates how several fundamental data types work. You’ll run the program to see what the data types look like, and then you’ll look at how the variables are declared and used in the program code. You’ll also learn where to place variable declarations so that they’re available to all the event procedures in your program.

  6. Click the Start button on the Standard toolbar.
  7. The following application window appears:

    (Image unavailable)

    The Data Types program lets you experiment with 11 data types, including integer, single-precision floating point, and date. The program displays an example of each type when you click its name in the list box.

  8. Click the Integer type in the list box.
  9. The number 37,500,000 appears in the Sample Data box, as shown in the following illustration. Note that neither the Short, Integer, nor Long data type allows you to insert or display commas in them. To display commas, you’ll need to use the Format function.

    (Image unavailable)

  10. Click the Date type in the list box.
  11. The date 3/1/1963 appears in the Sample Data box.

  12. Click each data type in the list box to see how Visual Basic displays it in the Sample Data box.
  13. Click the Quit button to stop the program.
  14. Now you’ll examine how the fundamental data types are declared at the top of the form and how they’re used in the ListBox1_SelectedIndexChanged event procedure.

  15. Double-click the form itself (not any objects on the form), and enlarge the Code Editor to see more of the program code.
  16. The Code Editor will look like this:

    (Image unavailable)

    At the top of the Code Editor, you’ll see a line that says "Windows Form Designer generated code". If you click the plus sign next to this line, you’ll see statements that Visual Basic adds to your project so that the objects placed on the form contain the correct properties and the form loads correctly. In previous versions of Visual Basic, this "setup" code wasn’t accessible, but now it exists in each form file so that you can examine the inner workings of your forms and fine-tune them if you want. (I don’t recommend customizing the Windows Forms Designer generated code until you’ve completed this book and feel very comfortable with Visual Basic programming!)

    Below the Windows Forms Designer generated code, you’ll see the dozen or so program statements I added to declare 11 variables in your program—one for each of the fundamental data types in Visual Basic. (I didn’t create an example for the Object type, but we’ll experiment with that in later chapters.) By placing each Dim statement here, at the top of the form’s code initialization area, I’m insuring that the variables will be valid, or will have scope, in all of the form’s event procedures. That way, I can set the value of a variable in one event procedure and read it in another. Normally, variables are valid only in the event procedure in which they’re declared. To make them valid across the form, you need to declare variables at the top of your form’s code.


    NOTE:
    I’ve given each variable the same name as I did in the data types table earlier in the chapter so that you can see the examples I showed you in actual program code.
  17. Scroll down in the Code Editor, and examine the Form1_Load event procedure.
  18. You’ll see the following statements that add items to the list box object in the program. (You might remember this syntax from Chapter 3—I used some similar statements there.)

    (Image unavailable)

  19. Scroll down and examine the ListBox1_SelectedIndexChanged event procedure.
  20. The ListBox1_SelectedIndexChanged event procedure processes the selections you make in the list box and looks like this:

    (Image unavailable)

    The heart of the event procedure is a Select Case decision structure. In the next chapter, we’ll discuss how this group of program statements selects one choice from many. For now, notice how each section of the Select Case block assigns a sample value to one of the fundamental data type variables and then assigns the variable to the Text property of the Label4 object on the form. I used code like this in Chapter 3 to process list box choices, and you can also use these techniques to work with list boxes and data types in your own programs.


    NOTE:
    If you have more than one form in your project, you need to declare variables in a slightly different way (and place) to give them scope throughout your program (that is, in each form that your project contains). The type of variable that you’ll declare is a public, or global, variable, and it’s declared in a code module (a special file that contains declarations and procedures not associated with a particular form.) For information about creating public variables in code modules, see Chapter 10.
  21. Scroll through the ListBox1_SelectedIndexChanged event procedure, and examine each of the variable assignments closely.
  22. Try changing the data in a few of the variable assignment statements and running the program again to see what the data looks like. In particular, you might try assigning values to variables that are outside their accepted range, as shown in the data types table presented earlier. If you make such an error, Visual Basic will add a jagged underline below the incorrect value in the Code Editor, and the program won’t run until you change it. To learn more about your mistake, you can hold the mouse over the jagged underlined value and read a short tooltip error message about the problem.

  23. If you made any changes you want to save to disk, click the Save All button on the Standard toolbar.

User-Defined Data Types:
Visual Basic also lets you create your own data types. This feature is most useful when you’re dealing with a group of data items that naturally fit together but fall into different data categories. You create a user-defined type (UDT) by using the Structure statement, and you declare variables associated with the new type by using the Dim statement. Be aware that the Structure statement cannot be located in an event procedure—it must be located at the top of the form, along with other variable declarations, or in a code module.

For example, the following declaration creates a user-defined data type named Employee that can store the name, date of birth, and hire date associated with a worker:

Structure Employee
    Dim Name As String
    Dim DateOfBirth As Date
    Dim HireDate As Date
End Structure

After you create a data type, you can use it in the program code for the form or module’s event procedures. The following statements use the new Employee type. The first statement creates a variable named ProductManager, of the Employee type, and the second statement assigns the name "Erick Cody" to the Name component of the variable:

Dim ProductManager As Employee
ProductManager.Name = "Erick Cody"

This looks a little similar to setting a property, doesn’t it? Visual Basic uses the same notation for the relationship between objects and properties as it uses for the relationship between user-defined data types and component variables.


Constants: Variables That Don’t Change

If a variable in your program contains a value that never changes (such as π, a fixed mathematical entity), you might consider storing the value as a constant instead of as a variable. A constant is a meaningful name that takes the place of a number or a text string that doesn’t change. Constants are useful because they increase the readability of program code, they can reduce programming mistakes, and they make global changes easier to accomplish later. Constants operate a lot like variables, but you can’t modify their values at runtime. They are declared with the Const keyword, as shown in the following example:

Const Pi As Double = 3.14159265

This statement creates a constant named Pi that can be used in place of the value of π in the program code. To make a constant available to all the objects and event procedures in your form, place the statement at the top of your form along with other variable and structure declarations that will have scope in all of the form’s event procedures. To make the constant available to all the forms and modules in a program (not just Form1), create the constant in a code module, with the Public keyword in front of it. For example:

Public Const Pi As Double = 3.14159265

The following exercise demonstrates how you can use a constant in an event procedure.


Use a constant in an event procedure:
  1. On the File menu, point to Open, and then click Project.
  2. The Open Project dialog box appears.

  3. Open the Constant Tester project in the c:\vbnet03sbs\chap05\constant tester folder.
  4. If the project’s form isn’t visible, click Form1.vb in Solution Explorer, and then click the View Designer button.
  5. The Constant Tester form appears in the Windows Forms Designer. Constant Tester is a skeleton program. The user interface is finished, but you need to type in the program code.

  6. Double-click the Show Constant button on the form.
  7. The Button1_Click event procedure appears in the Code Editor.

  8. Type the following statements in the Button1_Click event procedure:
  9. Const Pi As Double = 3.14159265
    Label1.Text = Pi


    TIP:
    The location you choose for your declarations should be based on how you plan to use the constants or the variables. Programmers typically keep the scope for declarations as small as possible, while still making them available for code that needs to use them. For example, if a constant is needed only in a single event procedure, you should put the constant declaration within that event procedure. However, you could also place the declaration at the top of the form code, which would give all the event procedures in your form access to it.
  10. Click the Start button on the Standard toolbar to run the program.
  11. Click the Show Constant button.
  12. The Pi constant appears in the label box, as shown here:

    (Image unavailable)

  13. Click the Quit button to stop the program.

Constants are useful in program code, especially in involved mathematical formulas, such as Area = πr2. The next section describes how you can use operators and variables to write similar formulas.

Working with Visual Basic Operators

A formula is a statement that combines numbers, variables, operators, and keywords to create a new value. Visual Basic contains several language elements designed for use in formulas. In this section, you’ll practice working with mathematical operators, the symbols used to tie together the parts of a formula. With a few exceptions, the mathematical symbols you’ll use are the ones you use in everyday life, and their operations are fairly intuitive. You’ll see each demonstrated in the following exercises.

Visual Basic includes the following operators:

Operator Description
+ Addition
Subtraction
* Multiplication
/ Division
\ Integer (whole number) division
Mod Remainder division
^ Exponentiation (raising to a power)
& String concatenation (combination)

Basic Math: The +, –, *, and / Operators

The operators for addition, subtraction, multiplication, and division are pretty straightforward and can be used in any formula where numbers or numeric variables are used. The following exercise demonstrates how you can use them in a program.


Work with basic operators:
  1. On the File menu, point to Open, and then click Project.
  2. Open the Basic Math project in the c:\vbnet03sbs\chap05\basic math folder.
  3. If the project’s form isn’t visible, click Form1.vb in Solution Explorer, and then click the View Designer button.
  4. The Basic Math form appears in the Windows Forms Designer. The Basic Math program demonstrates how the addition, subtraction, multiplication, and division operators work with numbers you type. It also demonstrates how you can use text box, radio button, and button objects to process user input in a program.

  5. Click the Start button on the Standard toolbar.
  6. The Basic Math program runs in the development environment. The program displays two text boxes in which you enter numeric values, a group of operator radio buttons, a box that displays results, and two button objects (Calculate and Quit).

  7. Type 100 in the Variable 1 text box, and then press Tab.
  8. The cursor moves to the second text box.

  9. Type 17 in the Variable 2 text box.
  10. You can now apply any of the mathematical operators to the values in the text boxes.

  11. Click the Addition radio button, and then click the Calculate button.
  12. The operator is applied to the two values, and the number 117 appears in the Result box, as shown here:

    (Image unavailable)

  13. Practice using the subtraction, multiplication, and division operators with the two numbers in the variable boxes. (Click Calculate to calculate each formula.)
  14. The results appear in the Result box. Feel free to experiment with different numbers in the variable text boxes. (Try a few numbers with decimal points if you like.) I used the Double data type to declare the variables, so you can use very large numbers if you like.

    Now try the following test to see what happens:

  15. Type 100 in the Variable 1 text box, type 0 in the Variable 2 text box, click the Division radio button, and then click Calculate.
  16. Dividing by zero is a no-no in mathematical calculations, because it produces an infinite result. But Visual Basic is able to handle this calculation and displays a value of Infinity in the Result text box. Being able to handle some divide-by-zero conditions is a new feature that Visual Basic .NET automatically provides.

  17. When you’ve finished contemplating this and other tests, click the Quit button.
  18. The program stops, and the development environment returns.


Now take a look at the program code to see how the results were calculated. Basic Math uses a few of the standard input controls you experimented with in Chapter 3 and an event procedure that uses variables and operators to process the simple mathematical formulas. The program declares its variables at the top of the form so that they can be used in all of the Form1 event procedures.


Examine the Basic Math program code:
  1. Double-click the Calculate button on the form.
  2. The Code Editor displays the Button1_Click event procedure. At the top of the form code, you’ll see the following statement that declares two variables of type Double:

    ‘Declare FirstNum and SecondNum variables
    Dim FirstNum, SecondNum As Double

    I used the Double type because I wanted a large, general purpose variable type that could handle many different numbers—integers, numbers with decimal points, very big numbers, small numbers, and so on. The variables are declared on the same line using the shortcut notation. Both FirstNum and SecondNum are of type Double, and they’ll be used to hold the values input in the first and second text boxes, respectively.

  3. Scroll down in the Code Editor to see the contents of the Button1_Click event procedure.
  4. Your screen will look like this:

    (Image unavailable)

    The first two statements in the event procedure transfer data entered into the text box objects into the FirstNum and SecondNum variables.

    ‘Assign text box values to variables
    FirstNum = TextBox1.Text
    SecondNum = TextBox2.Text

    The TextBox control handles the transfer with the Text property—a property that accepts text entered by the user and makes it available for use in the program. I’ll make frequent use of the TextBox control in this book. When it’s set to multiline and resized, it can display many lines of text—even a whole file!

    After the text box values are assigned to the variables, the event procedure determines which radio button has been checked, calculates the mathematical formula, and displays the result in a third text box. The first radio button test looks like this:

    ‘Determine checked button and calculate
    If RadioButton1.Checked = True Then
        TextBox3.Text = FirstNum + SecondNum
    End If

    Remember from Chapter 3 that only one radio button object in a group box object can be selected at once. You can tell whether a radio button has been selected by evaluating the Checked property. If it’s True, the button has been selected. If the Checked property is False, the button has not been selected. After this simple test, you’re ready to compute the result and display it in the third text box object. That’s all there is to using basic mathematical operators. (You’ll learn more about the syntax of If...Then tests, or decision structures, in Chapter 6.)


You’re done using the Basic Math program.

Using Advanced Operators: \, Mod, ^, and &

In addition to the four basic mathematical operators, Visual Basic includes four advanced operators, which perform integer division (\), remainder division (Mod), exponentiation (^), and string concatenation (&). These operators are useful in special-purpose mathematical formulas and text processing applications. The following utility (a slight modification of the Basic Math program) shows how you can use each of these operators in a program.


New Shortcut Operators:
An interesting new feature of Visual Basic .NET is that you can use shortcut operators for mathematical and string operations that involve changing the value of an existing variable. For example, if you combine the "+" symbol with the "=" symbol, you can add to a variable without repeating the variable name twice in the formula. Thus, you can write the formula X = X + 6 using the syntax X += 6. The following table shows examples of these shortcut operators:
Operation Long-form syntax Shortcut syntax
Addition (+) X = X + X += 6
Subtraction (-) X = X – 6 X -= 6
Multiplication (*) X = X * 6 X *= 6
Division (/) X = X / 6 X /= 6
Integer division (\) X = X \ 6 X \= 6
Exponentiation (^) X = X ^ 6 X ^= 6
String concatenation (&) X = X & "ABC" X &= "ABC"

Work with advanced operators:
  1. On the File menu, point to Open, and then click Project.
  2. The Open Project dialog box appears.

  3. Open the Advanced Math project in the c:\vbnet03sbs\chap05\advanced math folder.
  4. If the project’s form isn’t visible, click Form1.vb in Solution Explorer, and then click the View Designer button.
  5. The Advanced Math form appears in the Windows Forms Designer. The Advanced Math program is identical to the Basic Math program, with the exception of the operators shown in the radio buttons and in the program.

  6. Click the Start button on the Standard toolbar.
  7. The program displays two text boxes in which you enter numeric values, a group of operator radio buttons, a text box that displays results, and two buttons.

  8. Type 9 in the Variable 1 text box, and then press Tab.
  9. Type 2 in the Variable 2 text box.
  10. You can now apply any of the advanced operators to the values in the text boxes.

  11. Click the Integer Division radio button, and then click the Calculate button.
  12. The operator is applied to the two values, and the number 4 appears in the Result box, as shown here:

    (Image unavailable)

    Integer division produces only the whole number result of the division operation. Although 9 divided by 2 equals 4.5, the integer division operation returns only the first part, an integer (the whole number 4). You might find this result useful if you’re working with quantities that can’t easily be divided into fractional components, such as the number of adults that can fit in a car.

  13. Click the Remainder radio button, and then click the Calculate button.
  14. The number 1 appears in the Result box. Remainder division (modulus arithmetic) returns the remainder (the part left over that won’t evenly divide) after two numbers are divided. Because 9 divided by 2 equals 4 with a remainder of 1 (2 × 4 + 1 = 9), the result produced by the Mod operator is 1. In addition to adding an early-seventies quality to your code, the Mod operator can help you track "leftovers" in your calculations, such as the amount of change left over after a financial transaction.

  15. Click the Exponentiation radio button, and then click the Calculate button.
  16. The number 81 appears in the Result box. The exponentiation operator (^) raises a number to a specified power. For example, 9 ^ 2 equals 92, or 81. In a Visual Basic formula, 92 is written 9 ^ 2.

  17. Click the Concatenation radio button, and then click the Calculate button.
  18. The number 92 appears in the Result box. The string concatenation operator (&) combines two strings in a formula, but not through addition. The result is a combination of the "9" character and the "2" character. String concatenation can be performed on numeric variables—for example, if you’re displaying the inning-by-inning score of a baseball game as they do in old-time score boxes—but concatenation is more commonly performed on string values or variables.

    Because I declared the FirstNum and SecondNum variables as type Double, you can’t combine words or letters using the program code as written. Try the following test, for example, which will cause an error and end the program.

  19. Type birth in the Variable 1 text box, type day in the Variable 2 text box, verify that Concatenation is selected, and then click Calculate.
  20. Visual Basic is unable to process the text values you entered; the program stops running, and an error message appears on the screen, as shown here:

    (Image unavailable)

    This type of error is called a runtime error—an error that surfaces not during the design and compilation of the program, but later, when the program is running and encounters a condition it doesn’t know how to process. If this seems odd, you might imagine that Visual Basic is simply offering you a modern rendition of the robot plea "Does not compute!" from the best science fiction films of the 1950s. The updated computer-speak message "Cast from string ('birth') to Double is not valid" means that the words you entered in the text boxes ("birth" and "day") could not be assigned, or cast, by Visual Basic to variables of the type Double. Double types can only contain numbers. Period.

  21. Click the Continue button in the Microsoft Development Environment dialog box.
  22. If another Microsoft Development Environment dialog box is displayed indicating that no source code is available for the current location, click OK.

    Your program ends and returns you to the development environment. The Break button, which you’ll learn about in Chapter 8, allows you to use the debugging tools in Visual Studio to learn more about the defects, or bugs, in your program code.

    Now take a look at the program code to see how variables were declared and how the advanced operators were used.

  23. Scroll to the code at the top of the Code Editor. You’ll see the following comment and program statement:
  24. ‘Declare FirstNum and SecondNum variables
    Dim FirstNum, SecondNum As Double

    As you might recall from the previous exercise, FirstNum and SecondNum are the variables that hold numbers coming in from the TextBox1 and TextBox2 objects.

  25. Change the data type from Double to String now so that you can properly test how the string concatenation (&) operator works.
  26. Now scroll down in the Code Editor to see how the advanced operators are used in the program code. You’ll see the following code:
  27. ‘Assign text box values to variables
    FirstNum = TextBox1.Text
    SecondNum = TextBox2.Text
     
    ‘Determine checked button and calculate
    If RadioButton1.Checked = True Then
        TextBox3.Text = FirstNum \ SecondNum
    End If
    If RadioButton2.Checked = True Then
        TextBox3.Text = FirstNum Mod SecondNum
    End If
    If RadioButton3.Checked = True Then
        TextBox3.Text = FirstNum ^ SecondNum
    End If
    If RadioButton4.Checked = True Then
        TextBox3.Text = FirstNum & SecondNum
    End If

    Like the Bas ic Math program, this program loads data from the text boxes and places it in the FirstNum and SecondNum variables. The program then checks to see which radio button the user checked and computes the requested formula. In this event procedure, the integer division (\), remainder (Mod), exponentiation (^), and string concatenation (&) operators are used. Now that you’ve changed the data type of the variables to String, run the program again to see how the & operator works on text.

  28. Click the Start button.
  29. Type birth in the Variable 1 text box, type day in the Variable 2 text box, click Concatenation, and then click Calculate.
  30. The program now concatenates the string values and doesn’t produce a runtime error, as shown here:

    (Image unavailable)

  31. Click the Quit button to close the program.

You’re finished working with the Advanced Math program.


TIP:
Runtime errors are difficult to avoid completely—even the most sophisticated application programs, such as Microsoft Word or Microsoft Excel, run into error conditions they can’t handle sometimes, producing runtime errors, or crashes. Designing your programs to handle many different data types and operating conditions will help you produce solid, or robust, applications. In Chapter 9, you’ll learn about another helpful tool for preventing runtime error crashes—the structured error handler.

Working with Math Methods in the .NET Framework

Now and then you’ll want to do a little extra number crunching in your programs. You might need to round a number, calculate a complex mathematical expression, or introduce randomness into your programs. The math methods shown in the following table can help you work with numbers in your formulas. These methods are provided by the .NET Framework, a class library that lets you tap into the power of the Microsoft Windows operating system and accomplish many of the common programming tasks that you need to create your projects. The .NET Framework is a new feature of Visual Studio .NET that is shared by Microsoft Visual Basic, Microsoft Visual C++, Microsoft Visual C#, Microsoft Visual J#, and other tools in Visual Studio. It’s an underlying interface that becomes part of the Windows operating system itself. The .NET Framework is organized into classes that you can include by name in your programming projects by using the Imports statement. The process is quite simple, and you’ll experiment with how it works now by using a math method in the System.Math class of the .NET Framework.

The following table offers a partial list of the math methods in the System.Math class. The argument n in the table represents the number, variable, or expression you want the method to evaluate. If you use any of these methods, be sure that you put the statement

Imports System.Math

at the very top of your form code in the Code Editor.

Method Purpose
Abs(n) Returns the absolute value of n.
Atan(n) Returns the arctangent, in radians, of n.
Cos(n) Returns the cosine of the angle n. The angle n is expressed in radians.
Exp(n) Returns the constant e raised to the power n.
Sign(n) Returns –1 if n is less than 0, 0 if n is 0, and +1 if n is greater than 0.
Sin(n) Returns the sine of the angle n. The angle n is expressed in radians.
Sqrt(n) Returns the square root of n.
Tan(n) Returns the tangent of the angle n. The angle n is expressed in radians.

Use the System.Math class to compute square roots:
  1. On the File menu, point to New, and then click Project.
  2. The New Project dialog box appears.

  3. Create a new Visual Basic Windows Application project named My Framework Math in the c:\vbnet03sbs\chap05 folder.
  4. The new project is created, and a blank form appears in the Windows Forms Designer.

  5. Click the Button control on the Windows Forms tab of the Toolbox, and create a button object at the top of your form.
  6. Click the TextBox control in the Toolbox, and draw a text box below the button object.
  7. Set the Text property of the button object to Square Root, and set the Text property of the text box object to blank (empty).
  8. Double-click the button object to display the Code Editor.
  9. At the very top of the Code Editor, above the Public Class Form1 statement, type the following program statement:
  10. Imports System.Math

    The Imports statement adds a library of objects, properties, and methods to your project. This statement must be the first statement in your program—it must come even before the variables that you declare for the form and the Public Class Form1 statement that Visual Basic automatically provides. The particular library you’ve chosen is the System.Math class, a collection of objects, properties, and methods provided by the .NET Framework for mathematical operations.

  11. Move down in the Code Editor, and add the following code to the Button1_Click event procedure between the Private Sub and End Sub statements:
  12. Dim Result As Double
    Result = Sqrt(625)
    TextBox1.Text = Result

    These three statements declare a variable of the double type named Result, use the Sqrt method to compute the square root of 625, and assign the Result variable to the Text property of the text box object so that the answer will be displayed.

  13. Click the Save All button on the Standard toolbar to save your changes.
  14. Click the Start button on the Standard toolbar.
  15. The Framework Math program runs in the development environment.

  16. Click the Square Root button.
  17. Visual Basic calculates the square root of 625 and displays the result (25) in the text box, as shown here. The Sqrt method works!

    (Image unavailable)

  18. Click the Close button on the form to end the program.

To use a particular .NET Framework class in your program, include the Imports statement, and specify the appropriate class library. You can use this technique to use any class in the .NET Framework. You’ll see several more examples of this skill as you work through the book.

Operator Precedence

In the past few exercises, you experimented with several mathematical operators and one string operator. Visual Basic lets you mix as many mathematical operators as you like in a formula, as long as each numeric variable and expression is separated from another by one operator. For example, this is an acceptable Visual Basic formula:

Total = 10 + 15 * 2 / 4 ^ 2

The formula processes several values and assigns the result to a variable named Total. But how is such an expression evaluated by Visual Basic? In other words, what sequence of mathematical operators does Visual Basic use when solving the formula? You might not have noticed, but the order of evaluation matters a great deal in this example.

Visual Basic solves this dilemma by establishing a specific order of precedence for mathematical operations. This list of rules tells Visual Basic which operator to use first, second, and so on when evaluating an expression that contains more than one operator. The following table lists the operators from first to last in the order in which they’ll be evaluated. (Operators on the same level in this table are evaluated from left to right as they appear in an expression.)

Operators Order of Preference
( ) Values within parentheses are always evaluated first.
^ Exponentiation (raising a number to a power) is second.
Negation (creating a negative number) is third.
* / Multiplication and division are fourth.
\ Integer division is fifth.
Mod Remainder division is sixth.
+ – Addition and subtraction are last.

Given the order of precedence in this table, the expression

Total = 10 + 15 * 2 / 4 ^ 2

would be evaluated by Visual Basic in the following steps. (Boldface type is used to show each step in the order of evaluation and its result.)

Total = 10 + 15 * 2 / 4 ^ 2
Total = 10 + 15 * 2 / 16
Total = 10 + 30 / 16
Total = 10 + 1.875
Total = 11.875

One Step Further: Using Parentheses in a Formula

You can use one or more pairs of parentheses in a formula to clarify the order of precedence. For example, Visual Basic would calculate the formula

Number = (8 - 5 * 3) ^ 2

by determining the value within the parentheses (–7) before doing the exponentiation—even though exponentiation is higher in order of precedence than subtraction and multiplication, according to the preceding table. You can further refine the calculation by placing nested parentheses in the formula. For example,

Number = ((8 - 5) * 3) ^ 2

directs Visual Basic to calculate the difference in the inner set of parentheses first, perform the operation in the outer parentheses next, and then determine the exponentiation. The result produced by the two formulas is different: the first formula evaluates to 49 and the second to 81. Parentheses can change the result of a mathematical operation, as well as make it easier to read.

Lesson 5 Quick Reference

To Do this
Declare a variable Type Dim followed by the variable name, the As keyword, and the variable data type in the program code. To make the variable valid in all of the form’s event procedures, place this statement at the top of the code for a form, before any event procedures. For example:

Dim Country As String

Change the value of a variable Assign a new value with the assignment operator of (=). For example:

Country = "Japan"

Get input with a dialog box Use the InputBox function, and assign the result to a variable. For example:

UserName = InputBox("What is your name?")

Display output in a dialog box Use the MsgBox function. (The string to be displayed in the dialog box can be stored in a variable.) For example:

Forecast = "Rain, mainly on the plain."
MsgBox(Forecast, , "Spain Weather Report")

Create a constant Type the Const keyword followed by the constant name, the assignment operator (=), the constant data type, and the fixed value. For example:

Const JackBennysAge As Short = 39

Create a formula Link together numeric variables or values with one of the seven mathematical operators, and then assign the result to a variable or a property. For example:

Result = 1 ^ 2 * 3 \ 4  ’this equals 0

Combine text strings Use the string concatenation operator (&). For example:

Msg = "Hello" & "," & " world!"

Include a class library from the .NET Framework Place an Imports statement at the very top of the form’s code that identifies the class library. For example:

Imports System.Math

Make a call to a method from an included class library Use the method name, and include any necessary arguments so that it can be used in a formula or a program statement. For example, to make a call to the Sqrt method in the System.Math class library:

Hypotenuse = Sqrt(x ^ 2 + y ^ 2)

Control the evaluation order in a formula Use parentheses in the formula. For example:

Result = 1 + 2 ^ 3 \ 4       ’this equals 3
Result = (1 + 2) ^ ( 3 \ 4)  ’this equals 1

Read More Show Less

Customer Reviews

Be the first to write a review
( 0 )
Rating Distribution

5 Star

(0)

4 Star

(0)

3 Star

(0)

2 Star

(0)

1 Star

(0)

Your Rating:

Your Name: Create a Pen Name or

Barnes & Noble.com Review Rules

Our reader reviews allow you to share your comments on titles you liked, or didn't, with others. By submitting an online review, you are representing to Barnes & Noble.com that all information contained in your review is original and accurate in all respects, and that the submission of such content by you and the posting of such content by Barnes & Noble.com does not and will not violate the rights of any third party. Please follow the rules below to help ensure that your review can be posted.

Reviews by Our Customers Under the Age of 13

We highly value and respect everyone's opinion concerning the titles we offer. However, we cannot allow persons under the age of 13 to have accounts at BN.com or to post customer reviews. Please see our Terms of Use for more details.

What to exclude from your review:

Please do not write about reviews, commentary, or information posted on the product page. If you see any errors in the information on the product page, please send us an email.

Reviews should not contain any of the following:

  • - HTML tags, profanity, obscenities, vulgarities, or comments that defame anyone
  • - Time-sensitive information such as tour dates, signings, lectures, etc.
  • - Single-word reviews. Other people will read your review to discover why you liked or didn't like the title. Be descriptive.
  • - Comments focusing on the author or that may ruin the ending for others
  • - Phone numbers, addresses, URLs
  • - Pricing and availability information or alternative ordering information
  • - Advertisements or commercial solicitation

Reminder:

  • - By submitting a review, you grant to Barnes & Noble.com and its sublicensees the royalty-free, perpetual, irrevocable right and license to use the review in accordance with the Barnes & Noble.com Terms of Use.
  • - Barnes & Noble.com reserves the right not to post any review -- particularly those that do not follow the terms and conditions of these Rules. Barnes & Noble.com also reserves the right to remove any review at any time without notice.
  • - See Terms of Use for other conditions and disclaimers.
Search for Products You'd Like to Recommend

Recommend other products that relate to your review. Just search for them below and share!

Create a Pen Name

Your Pen Name is your unique identity on BN.com. It will appear on the reviews you write and other website activities. Your Pen Name cannot be edited, changed or deleted once submitted.

 
Your Pen Name can be any combination of alphanumeric characters (plus - and _), and must be at least two characters long.

Continue Anonymously

    If you find inappropriate content, please report it to Barnes & Noble
    Why is this product inappropriate?
    Comments (optional)