- •Using Your Sybex Electronic Book
- •Acknowledgments
- •Contents at a Glance
- •Introduction
- •Who Should Read This Book?
- •How About the Advanced Topics?
- •The Structure of the Book
- •How to Reach the Author
- •The Integrated Development Environment
- •The Start Page
- •Project Types
- •Your First VB Application
- •Making the Application More Robust
- •Making the Application More User-Friendly
- •The IDE Components
- •The IDE Menu
- •The Toolbox Window
- •The Solution Explorer
- •The Properties Window
- •The Output Window
- •The Command Window
- •The Task List Window
- •Environment Options
- •A Few Common Properties
- •A Few Common Events
- •A Few Common Methods
- •Building a Console Application
- •Summary
- •Building a Loan Calculator
- •How the Loan Application Works
- •Designing the User Interface
- •Programming the Loan Application
- •Validating the Data
- •Building a Math Calculator
- •Designing the User Interface
- •Programming the MathCalculator App
- •Adding More Features
- •Exception Handling
- •Taking the LoanCalculator to the Web
- •Working with Multiple Forms
- •Working with Multiple Projects
- •Executable Files
- •Distributing an Application
- •VB.NET at Work: Creating a Windows Installer
- •Finishing the Windows Installer
- •Running the Windows Installer
- •Verifying the Installation
- •Summary
- •Variables
- •Declaring Variables
- •Types of Variables
- •Converting Variable Types
- •User-Defined Data Types
- •Examining Variable Types
- •Why Declare Variables?
- •A Variable’s Scope
- •The Lifetime of a Variable
- •Constants
- •Arrays
- •Declaring Arrays
- •Initializing Arrays
- •Array Limits
- •Multidimensional Arrays
- •Dynamic Arrays
- •Arrays of Arrays
- •Variables as Objects
- •So, What’s an Object?
- •Formatting Numbers
- •Formatting Dates
- •Flow-Control Statements
- •Test Structures
- •Loop Structures
- •Nested Control Structures
- •The Exit Statement
- •Summary
- •Modular Coding
- •Subroutines
- •Functions
- •Arguments
- •Argument-Passing Mechanisms
- •Event-Handler Arguments
- •Passing an Unknown Number of Arguments
- •Named Arguments
- •More Types of Function Return Values
- •Overloading Functions
- •Summary
- •The Appearance of Forms
- •Properties of the Form Control
- •Placing Controls on Forms
- •Setting the TabOrder
- •VB.NET at Work: The Contacts Project
- •Anchoring and Docking
- •Loading and Showing Forms
- •The Startup Form
- •Controlling One Form from within Another
- •Forms vs. Dialog Boxes
- •VB.NET at Work: The MultipleForms Project
- •Designing Menus
- •The Menu Editor
- •Manipulating Menus at Runtime
- •Building Dynamic Forms at Runtime
- •The Form.Controls Collection
- •VB.NET at Work: The DynamicForm Project
- •Creating Event Handlers at Runtime
- •Summary
- •The TextBox Control
- •Basic Properties
- •Text-Manipulation Properties
- •Text-Selection Properties
- •Text-Selection Methods
- •Undoing Edits
- •VB.NET at Work: The TextPad Project
- •Capturing Keystrokes
- •The ListBox, CheckedListBox, and ComboBox Controls
- •Basic Properties
- •The Items Collection
- •VB.NET at Work: The ListDemo Project
- •Searching
- •The ComboBox Control
- •The ScrollBar and TrackBar Controls
- •The ScrollBar Control
- •The TrackBar Control
- •Summary
- •The Common Dialog Controls
- •Using the Common Dialog Controls
- •The Color Dialog Box
- •The Font Dialog Box
- •The Open and Save As Dialog Boxes
- •The Print Dialog Box
- •The RichTextBox Control
- •The RTF Language
- •Methods
- •Advanced Editing Features
- •Cutting and Pasting
- •Searching in a RichTextBox Control
- •Formatting URLs
- •VB.NET at Work: The RTFPad Project
- •Summary
- •What Is a Class?
- •Building the Minimal Class
- •Adding Code to the Minimal Class
- •Property Procedures
- •Customizing Default Members
- •Custom Enumerations
- •Using the SimpleClass in Other Projects
- •Firing Events
- •Shared Properties
- •Parsing a Filename String
- •Reusing the StringTools Class
- •Encapsulation and Abstraction
- •Inheritance
- •Inheriting Existing Classes
- •Polymorphism
- •The Shape Class
- •Object Constructors and Destructors
- •Instance and Shared Methods
- •Who Can Inherit What?
- •Parent Class Keywords
- •Derived Class Keyword
- •Parent Class Member Keywords
- •Derived Class Member Keyword
- •MyBase and MyClass
- •Summary
- •On Designing Windows Controls
- •Enhancing Existing Controls
- •Building the FocusedTextBox Control
- •Building Compound Controls
- •VB.NET at Work: The ColorEdit Control
- •VB.NET at Work: The Label3D Control
- •Raising Events
- •Using the Custom Control in Other Projects
- •VB.NET at Work: The Alarm Control
- •Designing Irregularly Shaped Controls
- •Designing Owner-Drawn Menus
- •Designing Owner-Drawn ListBox Controls
- •Using ActiveX Controls
- •Summary
- •Programming Word
- •Objects That Represent Text
- •The Documents Collection and the Document Object
- •Spell-Checking Documents
- •Programming Excel
- •The Worksheets Collection and the Worksheet Object
- •The Range Object
- •Using Excel as a Math Parser
- •Programming Outlook
- •Retrieving Information
- •Recursive Scanning of the Contacts Folder
- •Summary
- •Advanced Array Topics
- •Sorting Arrays
- •Searching Arrays
- •Other Array Operations
- •Array Limitations
- •The ArrayList Collection
- •Creating an ArrayList
- •Adding and Removing Items
- •The HashTable Collection
- •VB.NET at Work: The WordFrequencies Project
- •The SortedList Class
- •The IEnumerator and IComparer Interfaces
- •Enumerating Collections
- •Custom Sorting
- •Custom Sorting of a SortedList
- •The Serialization Class
- •Serializing Individual Objects
- •Serializing a Collection
- •Deserializing Objects
- •Summary
- •Handling Strings and Characters
- •The Char Class
- •The String Class
- •The StringBuilder Class
- •VB.NET at Work: The StringReversal Project
- •VB.NET at Work: The CountWords Project
- •Handling Dates
- •The DateTime Class
- •The TimeSpan Class
- •VB.NET at Work: Timing Operations
- •Summary
- •Accessing Folders and Files
- •The Directory Class
- •The File Class
- •The DirectoryInfo Class
- •The FileInfo Class
- •The Path Class
- •VB.NET at Work: The CustomExplorer Project
- •Accessing Files
- •The FileStream Object
- •The StreamWriter Object
- •The StreamReader Object
- •Sending Data to a File
- •The BinaryWriter Object
- •The BinaryReader Object
- •VB.NET at Work: The RecordSave Project
- •The FileSystemWatcher Component
- •Properties
- •Events
- •VB.NET at Work: The FileSystemWatcher Project
- •Summary
- •Displaying Images
- •The Image Object
- •Exchanging Images through the Clipboard
- •Drawing with GDI+
- •The Basic Drawing Objects
- •Drawing Shapes
- •Drawing Methods
- •Gradients
- •Coordinate Transformations
- •Specifying Transformations
- •VB.NET at Work: Plotting Functions
- •Bitmaps
- •Specifying Colors
- •Defining Colors
- •Processing Bitmaps
- •Summary
- •The Printing Objects
- •PrintDocument
- •PrintDialog
- •PageSetupDialog
- •PrintPreviewDialog
- •PrintPreviewControl
- •Printer and Page Properties
- •Page Geometry
- •Printing Examples
- •Printing Tabular Data
- •Printing Plain Text
- •Printing Bitmaps
- •Using the PrintPreviewControl
- •Summary
- •Examining the Advanced Controls
- •How Tree Structures Work
- •The ImageList Control
- •The TreeView Control
- •Adding New Items at Design Time
- •Adding New Items at Runtime
- •Assigning Images to Nodes
- •Scanning the TreeView Control
- •The ListView Control
- •The Columns Collection
- •The ListItem Object
- •The Items Collection
- •The SubItems Collection
- •Summary
- •Types of Errors
- •Design-Time Errors
- •Runtime Errors
- •Logic Errors
- •Exceptions and Structured Exception Handling
- •Studying an Exception
- •Getting a Handle on this Exception
- •Finally (!)
- •Customizing Exception Handling
- •Throwing Your Own Exceptions
- •Debugging
- •Breakpoints
- •Stepping Through
- •The Local and Watch Windows
- •Summary
- •Basic Concepts
- •Recursion in Real Life
- •A Simple Example
- •Recursion by Mistake
- •Scanning Folders Recursively
- •Describing a Recursive Procedure
- •Translating the Description to Code
- •The Stack Mechanism
- •Stack Defined
- •Recursive Programming and the Stack
- •Passing Arguments through the Stack
- •Special Issues in Recursive Programming
- •Knowing When to Use Recursive Programming
- •Summary
- •MDI Applications: The Basics
- •Building an MDI Application
- •Built-In Capabilities of MDI Applications
- •Accessing Child Forms
- •Ending an MDI Application
- •A Scrollable PictureBox
- •Summary
- •What Is a Database?
- •Relational Databases
- •Exploring the Northwind Database
- •Exploring the Pubs Database
- •Understanding Relations
- •The Server Explorer
- •Working with Tables
- •Relationships, Indices, and Constraints
- •Structured Query Language
- •Executing SQL Statements
- •Selection Queries
- •Calculated Fields
- •SQL Joins
- •Action Queries
- •The Query Builder
- •The Query Builder Interface
- •SQL at Work: Calculating Sums
- •SQL at Work: Counting Rows
- •Limiting the Selection
- •Parameterized Queries
- •Calculated Columns
- •Specifying Left, Right, and Inner Joins
- •Stored Procedures
- •Summary
- •How About XML?
- •Creating a DataSet
- •The DataGrid Control
- •Data Binding
- •VB.NET at Work: The ViewEditCustomers Project
- •Binding Complex Controls
- •Programming the DataAdapter Object
- •The Command Objects
- •The Command and DataReader Objects
- •VB.NET at Work: The DataReader Project
- •VB.NET at Work: The StoredProcedure Project
- •Summary
- •The Structure of a DataSet
- •Navigating the Tables of a DataSet
- •Updating DataSets
- •The DataForm Wizard
- •Handling Identity Fields
- •Transactions
- •Performing Update Operations
- •Updating Tables Manually
- •Building and Using Custom DataSets
- •Summary
- •An HTML Primer
- •HTML Code Elements
- •Server-Client Interaction
- •The Structure of HTML Documents
- •URLs and Hyperlinks
- •The Basic HTML Tags
- •Inserting Graphics
- •Tables
- •Forms and Controls
- •Processing Requests on the Server
- •Building a Web Application
- •Interacting with a Web Application
- •Maintaining State
- •The Web Controls
- •The ASP.NET Objects
- •The Page Object
- •The Response Object
- •The Request Object
- •The Server Object
- •Using Cookies
- •Handling Multiple Forms in Web Applications
- •Summary
- •The Data-Bound Web Controls
- •Simple Data Binding
- •Binding to DataSets
- •Is It a Grid, or a Table?
- •Getting Orders on the Web
- •The Forms of the ProductSearch Application
- •Paging Large DataSets
- •Customizing the Appearance of the DataGrid Control
- •Programming the Select Button
- •Summary
- •How to Serve the Web
- •Building a Web Service
- •Consuming the Web Service
- •Maintaining State in Web Services
- •A Data-Driven Web Service
- •Consuming the Products Web Service in VB
- •Summary
12 Chapter 1 GETTING STARTED WITH VB.NET
the process surprisingly similar to the process of building Windows applications. Web applications and Web services are discussed in detail in the last part of the book.
ASP.NET Web service A Web service is not the equivalent of a Windows service. A Web service is a program that resides on a Web server and services requests, just like a Web application, but it doesn’t return an HTML page. Instead, it returns the result of a calculation or a database lookup. Requests to Web services are usually made by another server, which is responsible for processing the data. A Web application that accepts a query for all VB books published by Sybex will return a page with the results. A Web service that accepts the same query will return an XML file with the results. The file will be used by the application that made the request to prepare a new page and send it to the client, or to populate a Windows form.
Web control library Just as you can build custom Windows controls to use with your Windows forms, you can create custom Web controls to use with your Web pages. Web controls are not discussed in this book, but once you’ve understood how ASP applications work and how Web applications interact with clients, you’ll be able to follow the examples in the documentation.
The other three templates in the New Project dialog box—Empty Project, Empty Web Project, and New Project In Existing Folder—are not project types, just a way to organize the new project yourself. When you create a new project of any of the previous types, Visual Studio creates a new folder named after the project and populates it with a few files that are necessary for the specific application type. A Windows application, for example, has a form, and the appropriate file is created automatically in the project’s folder when a new Windows application is created. With the last three types of projects, you’re responsible for creating and adding all the required items yourself.
Your First VB Application
In this section, we’ll develop a very simple application to demonstrate not only the design of the interface, but also how to code the application. We’ll build an application that allows the user to enter the name of their favorite programming language, and then we evaluate the choice. Objectively, VB is a step ahead of all other languages and it will receive the best evaluation. All other languages will get the same grade—good, but not VB.
Tip The project you will build in this section is called WindowsApplication1, and you can find it in this chapter’s folder on the CD. Copy the WindowsApplication1 folder from the CD to your hard disk, then clear the Read-Only attribute of the files in the folder. All the files you copy from the CD are read-only. To change this attribute (so that you can save the changes), select all the files in a project’s folder, right-click them, and select Properties. In the dialog box that appears, clear the box Read-Only.
You can open the project on the CD and examine it, but I suggest you follow the steps outlined in this paragraph to build the project from scratch. Start a new project, use the default name WindowsApplication1, and place a TextBox and a Button control on the form. Use the mouse to position and resize the controls on the form, as shown in Figure 1.8.
Copyright ©2002 SYBEX, Inc., Alameda, CA |
www.sybex.com |
YOUR FIRST VB APPLICATION 13
Figure 1.8
A simple application that processes a usersupplied string
Now we must insert some code to evaluate the user’s favorite language. Windows applications are made up of small code segments, called event handlers, which react to specific actions. In the case of our example, we want to program the action of clicking the button. When the user clicks the button, we want to execute some code that will display a message.
To insert some code behind the Button control, double-click the control and you’ll see the code window of the application, which is shown in Figure 1.9. The line “Private ...” is too long to fit on the printed page, so I’ve inserted a line-continuation character (an underscore) to break it into two lines. When a line is too long, you can break it into two lines by inserting the line continuation character. Alternatively, you can turn on the word wrap feature of the editor (you’ll see shortly how to adjust the editor’s properties). Notice that I’ve also inserted quite a bit of space before the second half of the first code line. It’s customary to indent continued lines so that they can be easily distinguished from the other lines.
Figure 1.9
The outline of a subroutine that handles the Click event of a Button control
The editor opened a subroutine, which is delimited by the following statements:
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
End Sub
Copyright ©2002 SYBEX, Inc., Alameda, CA |
www.sybex.com |
14 Chapter 1 GETTING STARTED WITH VB.NET
At the top of the main pane of the Designer, you will see two tabs named after the form: in Figure 1.9, they’re the Form1.vb [Design] tab and the Form1.vb tab. The first tab is the Windows Form Designer (where you build the interface of the application with visual tools) and the second is the code editor, where you insert the code behind the interface. At the top of the code editor, which is what you see in Figure 1.9, are two ComboBoxes. The one on the left contains the names of the controls on the form. The other one contains the names of events each control recognizes. When you select a control (or an object, in general) in the left list, the other list’s contents are adjusted accordingly. To program a specific event of a specific control, select the name of the control in the first list (the Objects list) and the name of the event in the right list (the Events list).
The Click event happens to be the default event of the Button control, so when you doubleclick a Button on the form, you’re taken to the Button1_Click subroutine. This subroutine is an event handler. An event handler is invoked automatically every time an event takes place. The event is the Click event of the Button1 control. Every time the Button1 control on the form is clicked, the Button1_Click subroutine is activated. To react to the Click event of the button, you must insert the appropriate code in this subroutine.
The name of the subroutine is made up of the name of the control, followed by an underscore and the name of the event. This is just the default name, and you can change it to anything you like (such as EvaluateLanguage, for this example, or StartCalculations). What makes this subroutine an event handler is the keyword Handles at the end of the statement. The Handles keyword tells the compiler what event this subroutine is supposed to handle. Button1.Click is the Click event of the Button1 control. If there were another button on the form, the Button2 control, you’d have to write code for a subroutine that would handle the Button2.Click event. Each control recognizes many events; for each control and event combination, you can provide a different event handler. Of course, we never program every possible event for every control.
Note As you will soon realize, the controls have a default behavior and handle the basic events on their own. The TextBox control knows how to handle keystrokes. The CheckBox control (a small square with a check mark) changes state by hiding or displaying the checkmark every time it’s clicked. The ScrollBar control moves its indicator (the button in the middle of the control) every time you click one of the arrows at the two ends. Because of this default behavior of the controls, you need not supply any code for the events of most controls on the form.
Rename Button1_Click subroutine to EvaluateLanguage. However, you shouldn’t change the name of the event this subroutine handles. If you change the name of the control after you have inserted some code in an event handler, the name of the event handled by the subroutine will be automatically changed. The name of the subroutine, however, won’t change.
Let’s add some code to the Click event handler of the Button1 control. When this button is clicked, we want to examine the text on the control and, if it’s “Visual Basic”, display a message; if not, we’ll display a different message. Insert the lines of Listing 1.1 between the Private Sub and End Sub statements. (I’m showing the entire listing here, but there’s no reason to retype the first and last statements.)
Copyright ©2002 SYBEX, Inc., Alameda, CA |
www.sybex.com |
YOUR FIRST VB APPLICATION 15
Listing 1.1: Processing a User-Supplied String
Private Sub EvaluateLanguage_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click
Dim language As String language = TextBox1.Text
If language = “Visual Basic” Then MsgBox(“We have a winner!”)
Else
MsgBox(language & “ is not a bad language.”) End If
End Sub
Here’s what this code does. First, it assigns the value of the TextBox1 control to the variable language. A variable is a named location in memory, where a value is stored. This memory location can be read later in the code or set to a different value. Variables are where we store the intermediate results of our calculation when we write code. Then the program compares the value of the language variable to the literal “Visual Basic”, and depending on the outcome of the comparison, it displays one of two messages. The MsgBox() function displays the specified message in a small window with the OK button. Users can view the message and then click the OK button to close the message box.
Even if you’re not familiar with the syntax of the language, you should be able to understand what this code does. Visual Basic is the simplest .NET language, and we will discuss the various aspects of the language in detail in the following chapters. In the meantime, you should try to understand the process of developing a Windows application: how to build the visible interface of the application, and how to program the events to which you want your application to react.
Making the Application More Robust
The code of our first application isn’t very robust. If the user doesn’t enter the string with the exact spelling shown in the listing, the comparison will fail. We can convert the string to uppercase and then compare it to “VISUAL BASIC” to eliminate differences in case. To convert a string to uppercase, use the ToUpper method of the string class. The following expression returns the string stored in the language variable, converted to uppercase:
language.ToUpper
We should also assume that the user may enter “VB” or “VB.NET”, so let’s modify our code as shown in Listing 1.2.
Listing 1.2: A More Robust String Comparison Technique
Private Sub EvaluateLanguage_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click
Dim language As String language = TextBox1.Text
Copyright ©2002 SYBEX, Inc., Alameda, CA |
www.sybex.com |