1.2. 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.)

Figure 1-4. Creating the new project


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.

1.2.1. 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.

1.2.2. 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.

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.

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.

Figure 1-6. Docking windows


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 x 1024.


1.2.3. 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.

1.2.4. 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).

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.

1.2.5. 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.

Naming Conventions

The name of the control: pnlBanner is an example of "Hungarian Notation ," named after Dr. Charles Simonyi, Chief Architect at Microsoft (born in Hungary), who is credited with inventing the idea of prefixing variable names with a letter (or series of letters) that indicates the variable type.

Hungarian notation makes much more sense in a programming language like C with a limited number of types, than it does in an object-oriented language like Visual Basic 2005 that has an unlimited number of types.

Microsoft discourages the use of Hungarian Notation in public variables and properties for .NET. The convention that many Visual Basic 2005 programmers have adopted, and which I will use in this book, is to use Hungarian notation only for controls . For example, text boxes will be named txt??? (e.g., txtName) and group boxes will be grp??? (e.g., grpEmployees), while labels will be named lbl??? (e.g., lblFirstName). And so forth.

For more on Hungarian Notation, see:

For more on Microsoft naming conventions , see:

and:

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpgenref/html/cpconnamingguidelines.asp


1.2.5.1. 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.

1.2.5.2. 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.)

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.

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.

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!

1.2.6. 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.

1.2.7. 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.

Figure 1-10. Button events


1.2.8. 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.

1.2.9. 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.")

Classes, Objects, and Derivation

A class defines a new type, extending the language beyond the built-in types, such as integer and string.

A type is a general category like car. You drive a particular car, but your car and my car both belong to the class cars; they are of type car.

An object is an individual instance of a type. Each individual car (your particular car, my particular car) is an object.

A class has methods (that tell you what the class can do) and properties (that hold values for instances of the class). For example, the class MessageBox has a Show method that does the work of drawing the MessageBox. It also has a number of properties, such as size. Each instance of the MessageBox will have a specific size; one MessageBox may be 100 x 150, another may be larger or smaller.

It is possible for one class to inherit from (or derive from) another class. Saying that ListBox inherits from Window indicates that it specializes Window (that is, a ListBox is a special type of Window). Inheritance creates the is-a relationship: a ListBox is-a (specialized form of) Window that includes all the methods and properties of Window but adds additional methods and properties of its own. It is also possible for ListBox to change the way it implements methods inherited from Window. Thus, a ListBox might Draw itself differently than another Window does.

Window is referred to as the base class, and ListBox is called the derived class. That is, ListBox derives its fundamental characteristics and behaviors from Window, and then specializes to its own particular needs.

When you define a method, you define its parameters. It is permissible to pass a derived type as a parameter in place of a base type. That is, if a Window is expected, it is permissible to pass a ListBox (which derives from Window) because a ListBox is-a Window.

Similarly, all event handlers take an instance of type EventArgs, so it is permissible to pass an instance of a class that derives from EventArgs. For example, when you write an event handler for the selection change event in a ListBox, you will be passed an instance of type ListViewItemSelectionChangedEventArgs that is derived from EventArgs. This specialized type of EventArgs class contains additional information that is only relevant to the selection change event, such as the property IsSelected.

.NET has a rooted inheritance hierarchy. Every type in .NET is considered to derive from the base class Object. Even built-in types (e.g., integer, Double, etc.) derive from Object. Thus, by declaring a method to take an object of type Object, you can accept any type whatsoever.

For further discussion, see Chapter 18.


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").

Shared Methods and Properties

The methods and properties of a class can be either instance members or shared members. Instance members are associated with an instance of the class (e.g., a particular MessageBox's location), while shared members are associated with the class itself. The advantage of shared methods and properties is that you may access them without first creating an instance of the class.

Thus, in the code for the All Employees button-click event handler, you want to call the Show method on a message box. Rather than having to write:

 Dim mbox as new MessageBox(...) mBox.Show(  ) 

you can just write:

 MessageBox.Show(...) 

The shared Show( ) method is not specific to an instance, but rather is associated with the entire class.

For further discussion, see Chapter 1.


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.

Overloading Methods

There are many parameters you might want to provide to the MessageBox's Show method depending on the circumstances. In some cases, you'd like to provide just a single string and let the message box worry about its title, buttons, and so forth. In other cases, you'd like to dictate the title, buttons, and icons to use, but you don't care about setting a default button. Rather than creating 24 different methods (e.g., ShowString, ShowStringAndChooseButtons, ShowStringAndChooseButtonsAndSetDefaultButton) the author of the MessageBox class created 21 variations of the Show method. This process of creating more than one method with the same name is called method overloading .

Each method must have a unique signature. The signature is the name and the parameters. You typically overload a method by varying either the number of parameters or the types of parameters or both (note that changing the name of a parameter does not vary the signature).

If you look at the help entry for the MessageBox Show method, you'll find 24 overloaded versions of this one method. Each has a unique signature; meaning that no two have the same number and type of parameters, and that is how the compiler knows which version you want.

For further discussion, see Chapter 18.


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.

Figure 1-11. Choosing the overloaded Show method


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 

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.

Figure 1-13. Testing the event handler


Enumerated Constants

It is helpful to group related constants into an enumeration. For example, you might declare an enumeration of Fahrenheit temperature constants using the following code:

 Enum Temperatures    CelsiusMeetsFahrenheit = -40    WickedCold = 0    FreezingPoint = 32    LightJacketWeather = 60    SwimmingWeather = 72    BoilingPoint = 212 End Enum 

You would refer to one of these enumerated constants through the name of the enumeration. For example, the freezing point of water would be referred to as:

 Temperatures.FreezingPoint 

Similarly, the buttons valid for a MessageBox are referred to through their enumeration, MessageBoxButtons, and this allows IntelliSense to present you with all the valid values.

For more, see Chapter 16.


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.


1.2.10. 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.

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).

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.

1.2.11. 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) 

Casting

When you cast an object, you tell the compiler "trust me, I know what this is." In the example shown:

 CType(sender, Button) 

you are saying to the compiler, "trust me, I happen to know that sender is really of type Button." This is perfectly fine, but if you get it wrong, this code will throw an exception.

As an alternative to CType you may use the DirectCast keyword, providing an expression as the first argument and the type to convert it to as the second argument. You can only do this if the two arguments have an inheritance relationship. Since Button does inherit from Object, you could have written:

 DirectCast(sender, Button) 

Because DirectCast can be somewhat more efficient, it is preferred where there is an inheritance relationship.

For still further discussion, see Chapter 16.


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.

Figure 1-15. Sharing event handlers




Programming Visual Basic 2005
Programming Visual Basic 2005
ISBN: 0596009496
EAN: 2147483647
Year: 2006
Pages: 162
Authors: Jesse Liberty

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net