Getting Started

The hardest part of any project, for me, is getting started. There is a simple problem of mental inertia that is overcome only by firing up Visual Studio 2005 and dragging some controls onto a form.

To begin, start Visual Studio 2005 and create a Visual Basic 2005 Windows application, as shown in Figure 1-4. (If you are already in Visual Studio 2005, choose File → New project.)

Creating the new project

Figure 1-4. Creating the new project

Warning

Visual Studio 2005 has short-cut keys for almost every important command. These key combinations are configurable, however, and it would be confusing to include short-cut keys in this book when yours may be different. The best way to learn the short-cut key combinations is to look at the menu choices as you go.

Once the project is created, you are put into the Designer, with a blank form (titled Form1). The Toolbox is typically on the left, the Solution explorer and Properties windows are usually on the right, and a number of other useful windows may be minimized on the bottom, as shown in Figure 1-5.

Rearranging Windows

You can rearrange all of these Visual Studio elements by dragging and dropping the various windows. While you are in the editor, drag one of the windows from its docked position. As soon as you begin to move the window around, the docking diamond appears, as seen in Figure 1-6.

As you move the window, the four arrows of the diamond point to where you may dock. If you place the cursor over one of the arrows, it darkens and the placement for the window is previewed. If the window can join a tabbed group, the center of the diamond darkens as you pass the cursor over it. Hover over the darkened center and release the mouse and your window is automatically added to the tabbed group.

Renaming and Sizing the Form

The very first step will be to rename the Form1.vb file to Welcome.vb. Visual Studio 2005 will do the necessary work to make the changes throughout the solution. To rename the file click on Form1.vb within the Solution explorer and either right-click and choose Rename or change the File Name property in the Properties window.

Designer window

Figure 1-5. Designer window

We'll also change the window caption on the form to say "Welcome to Northwind." Changes to the form are accomplished by clicking on the form and then editing the properties in the Properties window. In VB.NET, the Text property controls the window caption.

Tip

VB6 NOTE: If you're familiar with Visual Basic 6 or earlier, you may recall that a form's caption was defined by its Caption property, not its Text property. In addition to the Visual Basic Form object, controls such as Checkbox, CommandButton, Frame, Label, and Option had a Caption property for static, display-only text. In contrast, the Text property was used for text that could usually be modified by the user. In .NET controls, these have been replaced by a single Text property.

The next step is to resize the form, which you can do by grabbing and dragging one of the sizing handles on the form itself, or by setting its Size property (click on the form, then click on the Size property in the Properties window). Notice that Size is expandable, and under Size you can set Width and Height separately. Set the Width to 582 and the Height to 582.

Docking windows

Figure 1-6. Docking windows

Tip

The size that looks best for you may depend on your target screen resolution. The projects done in this book were created on monitors set to 1280 × 1024.

MinimumSize and MaximumSize

The form may be resized by your user. You can control how much your form may be made smaller or larger using the MinimumSize and MaximumSize properties. These default to 0,0, which effectively disables these properties.

For this form, you may well want to create a MinimumSize that prevents the user from hiding one or more of the group boxes, or you may choose to leave the properties at their default values, which allows the user to set the form to any convenient size.

Using Picture Boxes, Panels, and Labels

To place the logo in the upper lefthand corner, follow these steps:

  1. Right-click on the project in the Solution explorer and add a folder. Name it Images.

  2. Copy the LAlogo.gif file (downloaded with the source code for this book) into the Images directory.

  3. Add a PictureBox control to your form with Location 0, 0.

  4. Click on the Ellipsis button within the Image property of the Picture box. Import the GIF file. Size the picture box to fit (133,129).

To create the banner "Northwind Data Central" you'll use two more controls. First, drag a panel into position by just touching the logo. (Its Location property should be 133,0.) Drag the panel's sizing handles to make the panel as tall as the logo, and wide enough to fill the form. (Its Size should be 445,128.) Set its name to pnlBanner. Set its BackColor to White (click on BackColor, drop down the color picker, and pick either a standard or a custom color).

Tip

All links mentioned in this book are available as hyperlinks in the file ProgrammingVisualBasic2005links.html included with the downloadable source code.

Next, drag a label onto the Panel. Set its name to lblBanner and its BackColor to White. Set its ForeColor to Blue (type in the name Blue, or pick it from Custom colors). Open the Font property and set the font size to 24. In the Text property, type in the text you want, Northwind Data Central. The label will expand to fit the text. You may want to click on it and choose Format → CenterInForm → Horizontally—it will center itself in the panel.

Press F5 to run the application. You should see a logo across the top of your form.

Adding Group Boxes, Buttons, and Text Boxes

You are now ready to create your four groups (Employees, Customers, Orders, and Suppliers), as shown in the specification.

Begin by dragging a group box onto the form. Name it grpEmployees and set its Text property to Employees (which sets the text in the border of the group box). Drag a button into the group box and name it btnAllEmployees. Set its Text property to All Employees. Grab the side of the button and stretch it so that the words fit. A reasonable location for the group lbox is 29,162, and a reasonable size is 247,166.

Aligning controls

Visual Studio 2005 provides extensive help for aligning the controls in your form. As you add controls, blue alignment lines appear to show you how to align various controls. Alternately, you are free to select (Shift-click) two or more controls and then use the alignment menu choices under Format.

For example, if you'd like your button centered within the group box, select the button and choose Format → Center In Form → Horizontally.

Drag two text boxes onto the group box, right below the All Employees button, and name them txtEmployeeFirst and txtEmployeeLast. To center the two text boxes, you'll need to select them both (click on the first text box, and Shift-click to highlight the second). This group of two text boxes can now be centered by choosing Format → Center In Form → Horizontally.

Drag two labels onto the group box and use the blue alignment lines to place them below the text boxes. Name them lblEmployeeFirst and lblEmployeeLast and set their text to First Name and Last Name, respectively.

Finally, click on the All Employees button and copy and paste it in place. Drag the new button below the text boxes and labels. Name it btnEmployeesFind and set its Text property to Find.

All of the elements in the group box should now be centered horizontally; let's center them vertically as well. To do so, put the cursor in the upper lefthand corner and drag to the lower righthand corner, marking all the controls . Next, use the menu item Format → Center In Form → Vertically.

You will want to explore the impact of using the various Format options, including aligning objects, equalizing the spacing, and centering objects within the group box. You can also use the blue alignment lines to help you quickly realign the various controls.

Copying and moving controls

Once the group box looks the way you want, use the mouse to select the group box and copy and paste so that you have a duplicate (which is pasted on top of the original, offset slightly). You can now drag the new group box below the first group box. (When you click on the group box, a move handle will appear, as shown in Figure 1-7, which allows you to drag the group box where you desire.)

Move handles

Figure 1-7. Move handles

Rename the new group box grpOrders and set its text to Orders. Fix the text on the buttons and labels, and rename all the controls (e.g., btnAllOrders, etc.), as shown in Table 1-1.

Table 1-1. Controls for Orders

Control

ControlID

Notes

Button

btnOrders

Centered (like All Employees)

Textbox

txtOrdersBeginDate

Good size is 100,20

Textbox

txtOrdersEndDate

Align with first text box

Label

lblBeginDate

Text: Begin Date

Label

lblEndDate

Text: EdDate

Button

btnFind

Centered as before

Copy and paste a third group box and name it grpCustomers. Delete the text box and label on the left. Move the right text box and label, stretching out the text box for Customer Name. Change the Text property of the Label to Customer Name. Rename the control and change the Text property of btnAllCustomers to All Customers. The new group box should look like Figure 1-8.

Customer group box

Figure 1-8. Customer group box

Finally, copy this third group box and create a fourth group box for Suppliers, as shown in Table 1-2.

Table 1-2. Controls for Suppliers

Control

ControlID

Notes

Button

btnAllSuppliers

Centered

Textbox

txtSupplierName

Same size as for customers

Label

lblSupplierName

Test: Supplier Name

Button

btnFind

Centered as before

When you are done, you should have a form that looks more or less like Figure 1-9.

Completed welcome form

Figure 1-9. Completed welcome form

Once you get comfortable with the tools, this form should take about 10 minutes to create! The good news is you now have a working form; unfortunately, the buttons don't actually do anything yet!

Events

The logic you will eventually implement is this: if the user clicks (for example) All Employees, you will open a form with a Rolodex that will allow the user to scroll through all the Employees. That form will also allow the user to filter which Employees are shown and to jump to those Employees whose name begins with a specific letter. All of that will be implemented with fairly advanced features such as custom controls in Chapter 4, so for now we'll stub out these buttons.

You can, of course, have the buttons do nothing, but it would be nice to have them pop up a message box saying, "Not yet implemented."

To make that work, you'll need to respond to the button click event, and you'll need to put up a message box.

Every control "publishes" a number of events that other parts of your program can respond to or handle. Buttons, of course, publish a click event. The click event "fires" every time the button is clicked.

Buttons also publish events that fire when the button's size is changed, when its background color changes, when its image changes, when its cursor changes, for drag over or drag/drop and so forth. You can find the events for buttons by either checking the documentation, or by selecting a button in the designer and then, in the Properties window, clicking the lightning bolt. This lightning bolt button switches the property window to show the control's events, as shown in Figure 1-10.

Creating Event Handlers

You now have three ways to create the Click event handler:

  1. You can type a method name in the property box next to Click, to create a method handler with that name, and press Enter.

  2. You can click in that box and drop down the list of already existing event handlers. (In this case, there won't be any yet, but later in the program you can use this approach to share event-handler methods among more than one control. More on that idea shortly.)

  3. You can double-click in the property box. Visual Studio 2005 will name the method for you.

Whichever of these you decide on, Visual Studio 2005 will bring you to the code editor for the event handler. If you let Visual Studio 2005 name the method, you will find yourself inside a Sub named btnAllEmployees_Click.

Button events

Figure 1-10. Button events

Default Event Handler

Every control has a default event. In the case of the button, it is (no surprise) "Click." That is the event most often handled, and so the Button designer set it to be the default event. You can double-click on the button and Visual Studio 2005 will act as if you had single-clicked on the button and then double-clicked on the Click event—that is, it will create the btnAllEmployees_Click event handler and put the editor into that subroutine.

Event-Handler Parameters

The convention is for .NET Event handlers to take two parameters . The first is of type Object (see sidebar "Classes, Objects, and Derivation") and is filled at runtime with a reference to the object that triggered the event (in this case, the button).

The second is an object of type EventArgs or a type derived from EventArgs. EventArgs itself is not useful, but the types derived from EventArgs contain very pertinent information. (See the sidebar "Classes, Objects, and Derivation.")

In this case, we want to put up a message box saying that the handler has not yet been implemented. The Framework Class Library (FCL) that comes with .NET provides you with a number of useful classes , one of which is the MessageBox class. The MessageBox class has a shared method (see sidebar "Shared Methods and Properties") Show that is overloaded (see the sidebar "Overloading Methods").

When you type the word MessageBox and then type a period, Visual Studio 2005's IntelliSense will display all the shared members of the MessageBox class. (The shared members are displayed because you placed the dot after a type name; had you typed the dot after an instance variable, the nonshared members would be displayed.

Click on Show and type an open parenthesis, and you'll see a tool tip indicating that there are 21 overloaded versions of this method. You want the one that lets you put in text, a title, and which buttons and icon you want to appear, as shown in Figure 1-11.

As you are about to enter each parameter, the tool tip will describe what it is looking for. When you get to the choice for the MessageBoxButtons, the tool tip will offer you one of the allowed values. These values are enumerated constants (see sidebar "Enumerated Constants") and thus IntelliSense can help you make a valid choice, as shown in Figure 1-12.

Similarly, IntelliSense will help you choose one of the valid options for the icon. When you are done, your event handler will look like Example 1-1.

Choosing the overloaded Show method

Figure 1-11. Choosing the overloaded Show method

Message box button choices

Figure 1-12. Message box button choices

Example 1-1. btnAllEmployees Click event handler

Private Sub btnAllEmployees_Click(ByVal sender As System.Object, _
        ByVal e As System.EventArgs) Handles btnAllEmployees.Click
    MessageBox.Show("Not yet implemented", "Not Yet Implemented", _
        MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
End Sub

Tip

The code in this and all examples has been broken into shorter lines to fit within the book; in Visual Studio 2005 you will find the entire signature (name and parameters) for the method on a single line. If you break a line in Visual Basic 2005 you must use the line continuation character—an underscore (_)—preceded by a space.

Run the application and click on All Employees. A message box will pop up with the message, title, icon, and button you designated, as shown in Figure 1-13. Congratulations! You just wrote your first event handler.

Testing the event handler

Figure 1-13. Testing the event handler

Tip

VB6 NOTE: You may be wondering what happened to the MsgBox function, the standard Visual Basic language function for displaying a message box. The answer is that it still exists in Visual Basic (it's a part of the Interaction class of the Microsoft.VisualBasic namespace) and can still be called from your Visual Basic code just as you always did. (Interestingly, it can also be called from any other .NET-compliant language, like C#, although it needs to be called as a shared method of the Interaction class.) Moreover, the syntax of MsgBox is largely identical to its VB6 counterpart, except that the final two optional parameters (which specify the location of a help file and the help context ID in the help file that contains information about the MsgBox display) have been eliminated.

.NET uses the more versatile MessageBox.Show method rather than the VB6 MsgBox, and we will use MessageBox throughout this book.

Sharing Event Handlers

It is possible, and often much cleaner, for more than one event to share a single event handler. Since the functionality of All Employees, All Customers, All Orders, and All Suppliers is very similar, it might make sense to give all four of these a common event handler.

Tip

VB6 NOTE: In VB6 and earlier versions, you could share event handlers by creating a control array. When the control array's event handler was invoked, Visual Basic passed it a single parameter, the index of the control that had fired the event. The VB6 control array, however, is not supported by Visual Basic .NET, which offers a much more flexible method of sharing event handlers.

To do so, open the code editor and change the name of btnAllEmployees_Click to btnAll_Click. When you do, an underline will appear near the new method name. Clicking on the underline will open a smart tag, and dropping the smart tag will open a command offering to rename the function for you, as shown in Figure 1-14. Clicking this will not only rename the function in place, but will "fix up" all references to this function (including in the designer-generated code).

Change function name

Figure 1-14. Change function name

Return to the design mode, click on the All Employees button, and then click on the lightning bolt in the properties to see the Events. Notice that the handler associated with the click event is now btnAllClick. Copy and paste that event handler name to the Click event handler for the other three related buttons, or click on the button and then in the properties/events window click on the "click" event and use the drop-down menu of event handlers to pick the one you want to use. Run the application and you'll see that all four buttons now bring up the same message box.

Differentiating Which Button Was Pressed

While having shared event handlers is fine, you may need to know which button was actually pressed. In our simple case, it would be nice to have the error message reflect the button (e.g., "All Employees not yet implemented.").

You can do this by casting the object passed into the event handler to type Button (using the CType conversion function):

CType(sender, Button)

This call to CType returns an object of type Button, representing the button that caused the event to fire. You can ask that button for its Text property, and assign the string returned to a variable:

Dim buttonName As String = CType(sender, Button).Text

You can then add that variable into the message box's message:

MessageBox.Show(buttonName + " not yet implemented", "Not Yet Implemented", _
            MessageBoxButtons.OK, MessageBoxIcon.Exclamation)

Each button's message is specialized, as shown in Figure 1-15.

Sharing event handlers

Figure 1-15. Sharing event handlers

Get Programming Visual Basic 2005 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.