the visual basic.net coach 1 chapter 12 – advanced topics chapter objectives explain how to...
Post on 20-Dec-2015
216 views
TRANSCRIPT
The Visual Basic .NET Coach
1
Chapter 12 – Advanced Topics
Chapter Objectives
Explain how to properly handle errors using Try and Catch statements
Explain how to use the graphic objects to draw on other objects
Explain how to create menus
Explain how to create applications containing multiple forms
The Visual Basic .NET Coach
2
Chapter 12 – Advanced Topics
12.1 Improved Error Handling
Programs are not written without errors occurring.
Generic error messages will intimidate the user of the application.
You should try to prevent errors from occurring by validating input and not allowing situations to arise in code where the system does not know how to react.
Predicting all possible errors cannot always be accomplished.
Visual Basic .NET provides the Try, Catch, Finally block structure, allowing you to code error handling in your applications.
The syntax of the new structure is as follows:
Try
'Code to check for error
Catch When Err.Number = ErrorNumber
'Code to handle specific error
Catch When Err.Number = Another ErrorNumber
'Code to handle other specific error
Catch
'Code to handle all the other errors
Finally
'Code to execute directly after
End Try
The Visual Basic .NET Coach
3
Chapter 12 – Advanced TopicsCode placed in a Try-Catch structure can be checked for:
• individual errors with specific code written to handle each error
• all errors can be handled by one set of code
• specific errors and then allow all remaining errors to be handled by one set of code.
You can think of a Try-Catch structure as similar to a Select-Case structure.
Try-Catch will trap errors for is placed between the Try keyword and the first Catch statement.
Each Catch When statement can be set up to check for specific errors by checking the exact number of the error that occurred.
If the error occurs, then the code associated with the specific Catch When statement is executed.
If you create a Catch statement without a When condition, then the code associated with the Catch statement will execute whenever none of the previous Catch When statements match the error.
After Catch statements have been evaluated and possibly executed, the Finally statement allows you to specify code that will always execute.
This code will execute whether or not an error has occurred in the code you are testing.
The Visual Basic .NET Coach
4
Chapter 12 – Advanced TopicsArithmetic Error Example
Imagine if you had to perform a calculation between a series of Short variables to output the average commission, to the nearest dollar, for a salesperson over the summer.
The calculation might be coded as follows:
shtAverageCommision = (shtJuneSales + shtJulySales + _
shtAugustSales) / shtPeriod
The calculation adds the sales of the months June, July, and August and then divides them by the variable storing the number of months in the period.
There are two very obvious possible sources of error.
First, remember that a Short variable can have a maximum value of 32,767. If the addition of all three months is greater than 32,767, you could get an overflow error.
You also have to worry that the variable shtPeriod is not equal to zero, because if it is, you will get a divide by zero error when performing the calculation.
The Visual Basic .NET Coach
5
Chapter 12 – Advanced TopicsThe answer to these problems is to place the code inside a Try block as follows:
Try
'Code to check for error
shtAverageCommission = (shtJuneSales + shtJulySales + _
shtAugustSales) \ shtPeriod
Catch When Err.Number = 6
'Code to handle arithmetic overflow
MsgBox("Computing the average commission produced a mathematical error")
'set the average commission to a valid value
shtAverageCommission = 0
Catch 'Code to handle all other errors
MsgBox(" An " & Err.Description & _
" error occurred when computing the average summer commission")
'set the average commission to a valid value
shtAverageCommission = 0
Finally
'Code to execute directly after
End Try
The Visual Basic .NET Coach
6
Chapter 12 – Advanced TopicsOpen File Error
Errors can often occur when a resource is unavailable.
A very common resource that may be unavailable is a file.
Often a file path could be wrong or another user may lock the file and your application is restricted from gaining access.
When you are opening a file, you should always trap for an error.
Try
Dim FileStreamName As New FileStream("C:\Log.txt", FileMode.Open, _
FileAccess.Read)
Catch When Err.Number = 53
MsgBox(" An error occurred when opening the log file")
End Try
The Visual Basic .NET Coach
7
Chapter 12 – Advanced Topics
12.2 GraphicsYou are already familiar with displaying some graphics in your applications.
The picture box control allows you to display only images that were previously created.
With the additional built-in objects provided in Visual Basic .NET, you have the ability to draw figures in many creative ways.
Although the initial method of using the Graphics class may seem a little cumbersome, use Visual Basic .NET’s type ahead feature to help.
The Visual Basic .NET Coach
8
Chapter 12 – Advanced TopicsUsing graphics starts by including the System.Drawing namespace, which will give you access to numerous classes that, when used together, allow you to draw directly on a form.
Any drawing that you will accomplish will require the use of at least the Graphics and Pen objects as well as Color, Point, Rectangle, and Size objects to help specify exactly how you wish to draw.
The Graphics object represents the surface you will be drawing on as well as being the object that creates graphical images.
The Pen object will determine how you draw on the Graphics object.
We’ll introduce these features by showing you how to create a drawing of a man.
The Visual Basic .NET Coach
9
Chapter 12 – Advanced TopicsStep 1: Before you can draw anything on an object, you must create a Graphics object and then instantiate it.
This is done by declaring a Graphics object and then calling a CreateGraphics method of the form.
You can declare the Graphics object using the following code:
Dim grfGraphics As Graphics
To instantiate the object, you have to call the CreateGraphics method of the form. The easiest way to do this is to refer to the form using the Me keyword.
grfGraphics = Me.CreateGraphics
The Visual Basic .NET Coach
10
Chapter 12 – Advanced TopicsStep 2: A Pen object will be used to draw with the Graphics object.
There are four ways to declare a Pen object.
The simplest is just to select a color.
If you want to get fancy, you can also select a Brush object to draw with a little more style.
While the default width of a Pen object is 1, you can also specify how wide you wish your pen to draw.
To declare a Pen object, you can use the following syntax:
Dim PenName As New Pen(Color.ColorName, PenWidth)
• PenName: The name of the pen you are declaring and instantiating.
• ColorName: One of the predefined colors you can select.
• PenWidth: A single value indicating the width of the pen as it draws.
The Visual Basic .NET Coach
11
Chapter 12 – Advanced TopicsWhen you instantiate a Pen object, you will first select the color of the pen.
Selecting a color is accomplished by using the Color object.
The Color object gives you access to all the predefined colors in Visual Basic .NET. Type "Color." and a list of predefined colors will pop up.
When you select one of these, your color use is greatly simplified.
To create your Pen object to draw a red line with a width of 2, use the following code:
Dim penOurPen As New Pen(Color.Red, 2)
With the Pen object created, you can now draw with the Graphics object.
The Visual Basic .NET Coach
12
Chapter 12 – Advanced TopicsLet’s start by drawing the circular head.
The easiest way to do this is to use the Ellipse method of the Graphics object.
It takes a Pen as the first parameter and then the X and Y locations of the upper-left corner of a rectangle that bounds the circle or ellipse that you are drawing.
The syntax is as follows:
GraphicsObjectName.DrawEllipse(PenName, XLocation, YLocation, Width, Height)
The final two parameters are the length and width of the bounding rectangle.
The code to draw the head would be as follows:
grfGraphics.DrawEllipse(penOurPen, 50, 50 , 40, 40)
The Visual Basic .NET Coach
13
Chapter 12 – Advanced TopicsStep 3: To draw the body, you need to draw a straight line.
The Graphics object contains a method DrawLine that will allow you to do this.
Switch the color of the pen by changing the Color property of your pen.
PenOurPen.Color = Color.Blue
Step 4: Draw the line using the following syntax:
GraphicsObjectName.DrawLine(PenName, StartingXLocation, StartingYLocation, _
EndingXLocation, EndingYLocation)
The code required to draw your body can then be drawn with the following code:
grfGraphics.DrawLine(penOurPen, 70, 90, 70, 150)
The Visual Basic .NET Coach
14
Chapter 12 – Advanced TopicsStep 5: You can follow the same procedure to draw the arms and legs.
Set the color to yellow with the following code:
PenOurPen.Color = Color.Yellow
Step 6: Now you can draw the left and right arms with the following code:
grfGraphics.DrawLine(penOurPen, 70, 150, 55, 105)
grfGraphics.DrawLine(penOurPen, 70, 150, 85, 105)
Step 7: To add legs, since they are the same color, you do not have to change the Pen object.
You can simply use the following code to draw the two lines representing the legs:
grfGraphics.DrawLine(penOurPen, 70, 150, 45, 170)
grfGraphics.DrawLine(penOurPen, 70, 150, 95, 170)
The Visual Basic .NET Coach
15
Chapter 12 – Advanced TopicsStep 8: To draw the feet use the DrawRectangle method.
The DrawRectangle method takes two parameters: a Pen and a Rectangle.
You already have a Pen object created.
To create a Rectangle object you need a Point object and a Size object.
'Draw Feet
Dim rctFoot As Rectangle
Dim pntFoot As Point
Dim szeFoot As Size
szeFoot = New Size(20, 10)
'Left Foot
pntFoot = New Point(25, 160)
rctFoot = New Rectangle(pntFoot, szeFoot)
grfGraphics.DrawRectangle(penOurPen, rctFoot)
'Right Foot
pntFoot = New Point(95, 160)
rctFoot = New Rectangle(pntFoot, szeFoot)
grfGraphics.DrawRectangle(penOurPen, rctFoot)
The Visual Basic .NET Coach
16
Chapter 12 – Advanced TopicsStep 8 (Alternative): If you wanted to fill in the rectangle, you could use the FillRectangle method.
The FillRectangle method requires a Brush object instead of a Pen object.
There are many different types of brushes.
You can create brushes that paint a solid color, a pattern, or even a texture using a bitmap file. For simplicity, you will create a brush with a solid color.'Draw Feet
Dim rctFoot As Rectangle
Dim pntFoot As Point
Dim szeFoot As Size
Dim bshAdam As SolidBrush
bshAdam = New SolidBrush(Color.Yellow)
szeFoot = New Size(20, 10)
'Left Foot
pntFoot = New Point(25, 160)
rctFoot = New Rectangle(pntFoot, szeFoot)
grfGraphics.FillRectangle(bshAdam, rctFoot)
'Right Foot
pntFoot = New Point(95, 160)
rctFoot = New Rectangle(pntFoot, szeFoot)
grfGraphics.FillRectangle(bshAdam, rctFoot)
The Visual Basic .NET Coach
17
Chapter 12 – Advanced TopicsStep 9: The last step is to add text to the drawing.
You can control the font and the brush that you draw with.
The Font object can be created by specifying some or all of the parameters in the following syntax:
FontObject = New Font(FontName, FontSize, FontStyle)
• FontName: Specifies the name of the font to display.
• FontSize: Specifies the size of the font.
• FontStyle: Specifies the style of the font (bold, italics, etc.).
To create a Font object to display the text "Adam" in a bold Times 20-point font using the previously created SolidBrush, use the following code:
Dim fntAdam As Font
bshAdam = New SolidBrush(System.Drawing.Color.Black)
fntAdam = New Font("Times", 20, FontStyle.Bold)
grfGraphics.DrawString("Adam", fntAdam, bshAdam, 32, 180)
The Visual Basic .NET Coach
18
Chapter 12 – Advanced TopicsStep 9: The last step is to add text to the drawing.
You can control the font and the brush that you draw with.
The Font object can be created by specifying some or all of the parameters in the following syntax:
FontObject = New Font(FontName, FontSize, FontStyle)
• FontName: Specifies the name of the font to display.
• FontSize: Specifies the size of the font.
• FontStyle: Specifies the style of the font (bold, italics, etc.).
To create a Font object to display the text "Adam" in a bold Times 20-point font using the previously created SolidBrush, use the following code:
Dim fntAdam As Font
bshAdam = New SolidBrush(System.Drawing.Color.Black)
fntAdam = New Font("Times", 20, FontStyle.Bold)
grfGraphics.DrawString("Adam", fntAdam, bshAdam, 32, 180)
The Visual Basic .NET Coach
19
Chapter 12 – Advanced Topics12.3 Creating Menus Using the Menu Editor
Menus are present in almost every application.
Menus make commonly used options available to the user.
Observe the menu for Visual Basic .NET and the submenu and separator bars.
The Visual Basic .NET Coach
20
Chapter 12 – Advanced TopicsTo produce a menu, Visual Basic .NET provides the MainMenu object.
When the MainMenu object is placed on the form, it will not appear on the actual form itself
It will appear below it as did the objects associated with connecting to a database.
When the Menu object is placed on the form, you can design your menu simply by clicking on the Menu object and then typing your menu in the Type Here boxes that appear.
The Visual Basic .NET Coach
21
Chapter 12 – Advanced TopicsOnce the menu name is entered, menu placeholders appear.
Menu items can be placed in these placeholders, with additional placeholders appearing as each menu item is added.
The Visual Basic .NET Coach
22
Chapter 12 – Advanced TopicsOnce the menu name is entered, menu placeholders appear.
Menu items can be placed in these placeholders, with additional placeholders appearing as each menu item is added.
For each menu item, you will want to attach code to execute whenever the user selects it.
To attach code, just double-click on the menu item and place the code in the Click event code that appears, in the same way you would for a button object.
The Visual Basic .NET Coach
23
Chapter 12 – Advanced TopicsExample: Simple Menu Application
Menus can be used to provide an easy way to access an application’s commonly used functions.
To focus on your understanding of the operation of a menu, you will create an application that is as simple as possible.
Your application will display a label and a picture that show a race walking competition.
The application will contain two menus, one to modify the picture and one to modify the label.
The application should have a menu to modify the border of the picture.
It will contain menu items to add a border to the picture and another menu item to remove it.
The Label menu will contain a menu item that will increase the size of the font in the label and another menu item to reduce the size of the font in the label.
The menu items will be created to set the color of the text to black, blue, or red.
The Visual Basic .NET Coach
24
Chapter 12 – Advanced TopicsCreating the Race Walking Application
Building an Application with a Menu
Step 1: Add a MainMenu object to the form.
Step 2: Rename the MainMenu object to mnuRaceWalk.
Step 3: Click on the MainMenu object so the window with Type Here appears.
Step 4: Type "&Picture" as the title of the first menu.
Step 5: Just as all controls in Visual Basic .NET have a name, so should menus.
Name your Picture menu mnuPicture by typing "mnuPicture" in the Name property of the Properties window.
The Visual Basic .NET Coach
25
Chapter 12 – Advanced TopicsStep 6: You need to add the menu items that belong to the Picture menu.
To associate menu items with a menu, you need to first click on the Type Here box below the Picture menu so that the menu editor moves from the current menu to a space to create the menu item.
Step 7: Enter the new menu item. Type "&Add Border".
The Visual Basic .NET Coach
26
Chapter 12 – Advanced TopicsStep 8: Rename the menu item to mnuPictureAdd.
Step 9: You can add the second menu item in the same manner.
Click on the Type Here box below the mnuPictureAdd menu item and fill in &Remove Border and rename it mnuRemoveBorder.
The Visual Basic .NET Coach
27
Chapter 12 – Advanced TopicsStep 10: Click to the right of the Picture menu on the MainMenu object so that you can type in the Type Here box.
When you click, additional Type Here boxes will appear and the previous ones along with the Picture menu’s menu items will disappear.
Step 11: Type "&Label" for the second menu.
Step 12: Rename the menu to mnuLabel.
The Visual Basic .NET Coach
28
Chapter 12 – Advanced TopicsStep 13: You can now specify the first menu item of the Label menu.
First, you click on the Type Here box below the Label menu.
Specify Text and Name properties for the menu item.
In this case, the names will be &Grow and mnuLabelGrow, respectively.
The Visual Basic .NET Coach
29
Chapter 12 – Advanced TopicsStep 14: You can add the remaining menu items in the same manner.
Click on the Type Here box and fill in "&Shrink" and "mnuLabelShrink" for the Text and Name properties of this menu item.
Repeat this process for &Black and mnuLabelBlack, &Blue and mnuLabelBlue, and &Red and mnuLabelRed.
The Visual Basic .NET Coach
30
Chapter 12 – Advanced TopicsYou are now complete with creating the “shell” of your menu; however, you still must specify the code that will execute when the individual menu items are selected.
Adding the Label and Picture Box
This application would really be about nothing if you didn’t add a few controls to manipulate the menu items. Add a label and picture box control titling and showing a race walking event.
Step 1: Add a label control drawn as wide as the form.
Step 2: Change the Name of the label control to lblTitle.
Step 3: Change the Text of the label control to Race Walking Competition.
Step 4: Change the TextAlign to MiddleCenter.
Step 5: Change the FontStyle to Bold.
Step 6: Resize the form to fit an image 400 x 400 pixels wide.
Step 7: Add a picture box control to the form and size it so that it can fit an image.
Step 8: Change the Name of the picture box to picRaceWalk.
Step 9: Click on the Image property and select the RaceWalk.jpg file in the bin directory.
The Visual Basic .NET Coach
31
Chapter 12 – Advanced TopicsYou are now complete with creating the “shell” of your menu; however, you still must specify the code that will execute when the individual menu items are selected.
Adding the Label and Picture Box
This application would really be about nothing if you didn’t add a few controls to manipulate the menu items. Add a label and picture box control titling and showing a race walking event.
Step 1: Add a label control drawn as wide as the form.
Step 2: Change the Name of the label control to lblTitle.
Step 3: Change the Text of the label control to Race Walking Competition.
Step 4: Change the TextAlign to MiddleCenter.
Step 5: Change the FontStyle to Bold.
Step 6: Resize the form to fit an image 400 x 400 pixels wide.
Step 7: Add a picture box control to the form and size it so that it can fit an image.
Step 8: Change the Name of the picture box to picRaceWalk.
Step 9: Click on the Image property and select the RaceWalk.jpg file in the bin directory.
The Visual Basic .NET Coach
32
Chapter 12 – Advanced TopicsSpecifying Code to Execute
Each menu item has a Click event for which you can specify code to accomplish whatever the purpose of the menu item is.
Step 1: By clicking on the menu and then the menu item you desire, you will call up the Click event code for that menu item.
The Visual Basic .NET Coach
33
Chapter 12 – Advanced TopicsPrivate Sub mnuPictureAdd_Click(…
End Sub
Menu item Click event code
Step 2: Now you can just add your code to set a border around your picture:
Private Sub mnuPictureAdd_Click(…
'Change the border style to a fixed 3D border
picRacewalk.BorderStyle = BorderStyle.Fixed3D
End Sub
Step 3: To add the code to the menu item mnuRemoveBorder, you just repeat the process.
Private Sub mnuPictureRemove_Click(…
'Remove the border style by setting it to None
picRacewalk.BorderStyle = BorderStyle.None
End Sub
The Visual Basic .NET Coach
34
Chapter 12 – Advanced TopicsStep 4: Repeat this process for the remaining menu items: mnuLabelGrow, mnuLabelShrink, mnuLabelBlack, mnuLabelBlue, and mnuLabelRed.
Private Sub mnuLabelGrow_Click(…
'Increase the Font by creating a new Font from the current Font
'with a font size of 1 greater than the font
lblTitle.Font = New Font("Microsoft Sans Serif", lblTitle.Font.Size + 1, _
FontStyle.Bold)
End Sub
Private Sub mnuLabelShrink_Click(…
'Increase the Font by creating a new Font from the current Font
'with a font size of 1 less than the font
lblTitle.Font = New Font("Microsoft Sans Serif", lblTitle.Font.Size - 1, _
FontStyle.Bold)
End Sub
Private Sub mnuLabelBlack_Click(…
'Change the font to the color black
lblTitle.ForeColor = Color.Black
End Sub
Private Sub mnuLabelBlue_Click(…
'Change the font to the color blue
lblTitle.ForeColor = Color.Blue
End Sub
Private Sub mnuLabelRed_Click(…
'Change the font to the color red
lblTitle.ForeColor = Color.Red
End Sub
The Visual Basic .NET Coach
35
Chapter 12 – Advanced TopicsWhen you are done, the application will look like:
The Visual Basic .NET Coach
36
Chapter 12 – Advanced TopicsAdding a Separator Line
As menu controls grow in size, it is often helpful to divide them into groups of common functionality by separator lines.
A separator line would be helpful to divide the menu items to change the size of the font from those that change the color of the font.
To add a separator line, just place a hyphen in the Type Here box of the menu editor.
The Visual Basic .NET Coach
37
Chapter 12 – Advanced TopicsAdding a Submenu
Although a separator line is a good way of breaking up a large menu, at some point too many menu items under one menu becomes cumbersome.
A submenu is an excellent way to combat this.
The Visual Basic .NET Coach
38
Chapter 12 – Advanced TopicsCreating a Submenu
Previously, you were told to ignore the Type Here box to the right of menu items. By typing in them, you can create a submenu.
Step 1: Change the first Label menu item’s Name and Text properties to mnuLabelSize and Change Size, respectively.
Step 2: Click on the Type Here box to the right of the mnuLabelSize menu item.
Step 3: Set the Name and Text properties to mnuLabelSizeGrow. and &Grow.
Step 4: Click on the Type Here box below the mnuLabelSizeGrow menu item.
Step 5: Set the Name and Text properties to mnuLabelSizeShrink. and &Shrink.
Step 6: To create the second submenu, click below the mnuLabelSize menu item in the Type Here box.
Step 7: Set the Name and Text properties to mnuLabelColor. and Change &Color.
Step 8: Click on the Type Here box to the right of the mnuLabelColor menu item.
Step 9: Set the Name and Text properties to mnuLabelColorBlack. and &Black.
Step 10: Repeat the process for the remaining submenu items.
The Visual Basic .NET Coach
40
Chapter 12 – Advanced Topics12.4 Multiple Form Applications
All of the applications you have developed so far have been limited to a single form or an SDI (Single Document Interface).
This limits the functionality of your applications.
You will first start with a simple application that does not consider the many issues that arise when you use applications with more than one form.
Showing Another Form
To open another form from the current form is a simple matter of using the Show method of a form.
The syntax is as simple as
FormName.Show
The Visual Basic .NET Coach
41
Chapter 12 – Advanced TopicsHiding or Unloading a Form
Once a form has been loaded, you can make the form disappear two ways.
If you want the form to merely disappear from the screen but still remain in memory, use the Hide event.
The syntax for hiding a form is as follows:
FormName.Hide
The other option for making a form disappear is to remove it both from the screen and the computer’s memory.
This is accomplished with the Unload command.
When a form is unloaded, unless the information that was entered into it is saved elsewhere, it will be lost.
The syntax for unloading a form is as follows:
Me.Close()
The Visual Basic .NET Coach
42
Chapter 12 – Advanced TopicsExample: Personnel Information
Now that you can create an application with more than one form, you can increase the amount of information you can gather in a single application.
For simplicity, you will create an application that gathers personnel information, but it will not save the information anywhere.
The case study at the end of the chapter will demonstrate that.
Your application will contain three forms: frmPersonnel, frmDemographics, and frmFinancial.
Each will contain different information about a person working for a company.
The first form that the user will be presented with is frmPersonnel.
The Visual Basic .NET Coach
43
Chapter 12 – Advanced TopicsThe Personnel form is the main form of your application.
It is the form that will be presented to the user when the application starts.
From it, you will be able to call both the Demographics and Financial forms.
These forms will be displayed when the btnDemographics or btnFinancial buttons are clicked.
The btnProfit button will display a message box containing information from the additional forms of the application.
The Visual Basic .NET Coach
44
Chapter 12 – Advanced TopicsThe Demographics form will contain an individual’s demographic information.
Notice that we have displayed information from the frmPersonnel form (my name) and added the btnHide button.
The btnHide button will allow the user to remove the form from the computer screen without removing it from the computer’s memory.
The Visual Basic .NET Coach
45
Chapter 12 – Advanced TopicsThe Financial form will contain an individual’s financial information.
Your Financial form contains text boxes to enter the number of hours and the rate at which an individual billed and worked.
Typically, consultants may work more hours than they can bill.
Consultants will be billed out at a higher rate than they are getting paid.
The Visual Basic .NET Coach
46
Chapter 12 – Advanced TopicsSharing Data Across Multiple Forms
While the code to instantiate and open the additional forms is rather trivial, a bit more thought is required in coding your application to share data across forms.
If you try to access an object on one form from another form, you will get a scoping error.
Objects created on one form are scoped to Private by default.
You will require the frmDemographics form’s txtTitle’s Text value to be accessible from the Personnel form.
You will wish to make the txtHomePhone’s Text value accessible.
The easiest way to accomplish this is to add a series of Property statements to the frmDemographics form giving access to the required properties.
Public Property Title() As String
Get
Return lblTitle.Text
End Get
Set(ByVal Value As String)
lblTitle.Text = Value
End Set
End Property
Public Property HomePhone() As String
Get
Return txtHome.Text
End Get
Set(ByVal Value As String)
txtHome.Text = Value
End Set
End Property
The Visual Basic .NET Coach
47
Chapter 12 – Advanced TopicsOn the frmFinancial’s form, you will require access to the txtTitle’s Text value as well as the profit amount.
Create a property called Profit that is automatically calculated when accessed.
Public Property Title() As String
Get
Return lblTitle.Text
End Get
Set(ByVal Value As String)
lblTitle.Text = Value
End Set
End Property
Public Property Profit() As String
Get
'Profit = Billables - Payables
Return (FormatCurrency((Val(txtBHours.Text) * Val(txtBRate.Text)) - _
(Val(txtPHours.Text) * Val(txtPRate.Text))))
End Get
Set(ByVal Value As String)
'Nothing happens, can't set the profit directly
End Set
End Property
The Visual Basic .NET Coach
48
Chapter 12 – Advanced TopicsCalling and Hiding Forms
The frmPersonnel form is the driver of the application.
It will instantiate and call an instantiation of the frmDemographic and frmFinancial forms.
Since the instances of the form will be accessed from more than one place in the frmPersonnel form, it is necessary to create a property for each to prevent the developer from making them visible to the entire form.
Add the following code in the form’s declaration section:
Private frmDemo As frmDemographics
Private frmFinance As frmFinancials
The Visual Basic .NET Coach
49
Chapter 12 – Advanced TopicsWhile the previous code declares the objects of each form, it does not instantiate them.
Each form will be instantiated when the user clicks on the button associated with each form.
In addition to instantiating them, the code will also set the Title property you created for the form so that it is personalized with the name of the person specified on the frmPersonnel form.
The final step is to display the newly instantiated and initialized form. The code for both buttons follows:
Private Sub btnDemographics_Click(…
frmDemo = New frmDemographics()
frmDemo.Title = "Demographics for " & txtFirstName.Text & _
" " & txtLastName.Text
frmDemo.Show()
End Sub
Private Sub btnFinancial_Click(…
frmFinance = New frmFinancials()
frmFinance.Title = "Financials for " & txtFirstName.Text & " " & _
txtLastName.Text
frmFinance.Show()
End Sub
The Visual Basic .NET Coach
50
Chapter 12 – Advanced TopicsWhile the previous code declares the objects of each form, it does not instantiate them.
Each form will be instantiated when the user clicks on the button associated with each form.
In addition to instantiating them, the code will also set the Title property you created for the form so that it is personalized with the name of the person specified on the frmPersonnel form.
The final step is to display the newly instantiated and initialized form. The code for both buttons follows:
Private Sub btnDemographics_Click(…
frmDemo = New frmDemographics()
frmDemo.Title = "Demographics for " & txtFirstName.Text & _
" " & txtLastName.Text
frmDemo.Show()
End Sub
Private Sub btnFinancial_Click(…
frmFinance = New frmFinancials()
frmFinance.Title = "Financials for " & txtFirstName.Text & " " & _
txtLastName.Text
frmFinance.Show()
End Sub
The Visual Basic .NET Coach
51
Chapter 12 – Advanced TopicsThe last code required on the frmPersonnel form is to display the profitability message when the btnProfit button is clicked.
The code is merely a concatenation of Strings that are accessible from the frmPersonnel form and the property statements of the frmDemographic and frmFinancial forms.
Private Sub btnProfit_Click(…
MsgBox(txtFirstName.Text & " " & txtLastName.Text & " Net Profit is " & _
frmFinance.Profit & ". He can be reached at " & _
frmDemo.HomePhone, MsgBoxStyle.OKOnly, "Profit")
End Sub
The Visual Basic .NET Coach
52
Chapter 12 – Advanced TopicsWhat to Do When the First Form Created Isn’t the First Form to Be Displayed
When you created your applications, you made sure that you first created the form that you wanted displayed as the default form of the application.
However, this is not always a practical solution. Therefore, Visual Basic .NET allows you to manually set the form to be displayed.
Step 1: Right-click on the MultiFormApp icon in the Solution Explorer.
Step 2: Click on the menu item Properties. The window below appears.
Step 3: Select the form that you wish to be the first form executed.
The Visual Basic .NET Coach
53
Chapter 12 – Advanced TopicsGlobal Variables
Way back toward the beginning of the text a brief mention was made of global variables.
A global variable is one that is visible to the entire application.
You have just seen how forms need to access data from each other.
In some cases, it is easier to have a global variable that every form in the application can access without having to create the property statements that you did.
You can create a Shared variable in a Public class.
When you add a single class to your application with only Public Shared properties declared within, all forms in the application will have access to it.
You may wonder what the difference is between a class defined in this manner versus using property statements.
The syntax is less cumbersome.
An object of this class does not need to be declared or instantiated within your application.
If you create a class as follows, it exists once for the entire application without the need to declare it.
Public Class ClassName
Public Shared VariableName As VariableType
End Class
The Visual Basic .NET Coach
54
Chapter 12 – Advanced Topics12.5 Multiple Document Interface (MDI)
Although the multiform application you just developed is an improvement over the single-formed applications you previously developed, it does not behave in the same manner as some multiform Windows applications with which you are familiar.
Applications like Microsoft Word are enclosed in a single parent form having child forms contained within it.
The choice of using MDI over the previous multiform implementation is mainly one of style and is easy to implement.
The Visual Basic .NET Coach
55
Chapter 12 – Advanced TopicsCreating MDI Documents
The creation and operation of an MDI application does not vary much from other multiform applications.
It requires designating one form as the parent form and attaching the other forms as children.
To define a form as the MDI parent, you must set the IsMDIContainer property of the form to True.
To define a form as the MDI child, you must set the MdiParent property of the child form to the parent form.
Add the following code to the child window menu options:
Private Sub mnuWindowDemographics_Click(...
frmDemo = New frmDemographics()
frmDemo.MdiParent = Me
frmDemo.Title = "Demographics for " & frmPerson.FullName
frmDemo.Show()
End Sub
Private Sub mnuWindowFinancial_Click(...
frmFinance = New frmFinancials()
frmFinance.MdiParent = Me
frmFinance.Title = "Financials for " & frmPerson.FullName
frmFinance.Show()
End Sub
Private Sub mnuWindowPersonnel_Click(...
frmPerson = New frmPersonnel()
frmPerson.MdiParent = Me
frmPerson.Show()
End Sub
The Visual Basic .NET Coach
59
Chapter 12 – Advanced TopicsTo arrange the child windows, you must call the LayoutMdi method of the parent form as in the following syntax:
MDIFormName.LayoutMDI(LayoutConstant)
The layout constant is defined in the System.Windows.Forms.MdiLayout object.
Private Sub mnuArrangeCascade_Click(...
Me.LayoutMdi(System.Windows.Forms.MdiLayout.Cascade)
End Sub
Private Sub mnuArrangeHoriz_Click(...
Me.LayoutMdi(System.Windows.Forms.MdiLayout.TileHorizontal)
End Sub
Private Sub mnuArrangeVert_Click(...
Me.LayoutMdi(System.Windows.Forms.MdiLayout.TileVertical)
End Sub
The Visual Basic .NET Coach
60
Chapter 12 – Advanced Topics12.6 Case Study
Problem Description
Your final case study will combine many of the concepts you have learned throughout the text. By combining databases, menus, and multiform applications, you are now ready to develop a fairly usable application.
The Visual Basic .NET Coach
61
Chapter 12 – Advanced TopicsThe three forms will display information in three tables from a new payroll database.
The database stores employee information, financial data, and phone numbers for a group of people.
Often more information is maintained about a single person than you may wish to display in a single form. .
This application will display financial and contact information for the employee currently selected in the data grid of the Employee Information form.
Problem Discussion
The Access database containing the three tables is provided for you in the Chapter 12 directory of your CD.
Employee Table
Field Name Data Type Size
ID AutoNumber N/A
LastName Text 20
FirstName Text 15
Address1 Text 50
Address2 Text 50
City Text 20
State Text 2
Zip Text 5
The Visual Basic .NET Coach
62
Chapter 12 – Advanced TopicsPayroll Table
Field Name Data Type Size
ID Long Integer N/A
HoursWorked Single N/A
Department Text 30
Day Date/Time N/A
DailyPay Currency N/A
Phone Number Table Field Name Data Type Size
ID Long Integer N/A
HomePhone Text 14
WorkPhone Text 14
MobilePhone Text 14
The Visual Basic .NET Coach
63
Chapter 12 – Advanced TopicsProblem Solution
Create a project called Employee.
Setting Up the Employee Information Form
Step 1: Rename the default form to frmEmployee.
Step 2: Change the Text property of the form to Employee Information.
Step 3: Create a data connection to the payroll database in Chapter 12’s case study’s code directory (located in the bin directory).
Step 4: Create a data adapter with a query that selects all the fields in the Employee table.
Step 5: Generate a data set called dsEmployee.
Step 6: Add a data grid called grdEmployees to the form.
Step 7: Set the data grid’s DataSource property to DsEmployee1.
Step 8: Set the data grid’s Anchor property to Top, Bottom, Left, Right.
Step 9: Add a button called btnFinancial with a Text property of View &Financial to the frmEmployee form.
Step 10: Add a button called btnPhone with a Text property of View &Phone to the frmEmployee form.
Step 11: Add a main menu called mnuWindow with a Text property of &Window to the frmEmployee form.
Step 12: Add a menu item called mnuWindowFinancial with a Text property of View &Financial to the mnuWindow menu.
Step 13: Add a menu item called mnuWindowPhone with a Text property of View &Phone to the mnuWindow menu.
The Visual Basic .NET Coach
64
Chapter 12 – Advanced TopicsSetting Up the Financial Information Form
Step 1: Create a new window’s form and name it frmFinancials.
Step 2: Change the Text property of the form to Financial Information.
Step 3: Create a data adapter, using the data connector you previously created, with a query that selects all the fields in the Payroll table with a parameter on the ID field in the WHERE clause.
Step 4: Generate a data set called dsPayroll1.
Step 5: Add a data grid called grdFinancial to the form.
Step 6: Set the data grid’s DataSource property to dsPayroll1.Payroll.
Step 7: Set the data grid’s Anchor property to Top, Bottom, Left, Right.
Step 8: When the Financial Information form is called, you must query the database and load the data grid with only the financial records of the employee indicated by the row selected in the data grid of the Employee form. All the coding required can be written in the Set statement of the property.
Private intEmployee As Integer
Public Property EmployeeID()
Get
'Nothing goes here, no need
End Get
Set(ByVal Value)
intEmployee = Value
OleDbDataAdapter1.SelectCommand.Parameters(0).Value = Employee
OleDbDataAdapter1.Fill(dsPayroll1)
End Set
End Property
The Visual Basic .NET Coach
65
Chapter 12 – Advanced TopicsSetting Up the Contact Information Form
Step 1: Create a new form and name it frmContact.
Step 2: Change the Text property of the form to Contact Information.
Step 3: Create a data adapter, using the data connector you previously created, with a query that selects all the fields in the PhoneNumbers table with a parameter on the ID field in the WHERE clause.
Step 4: Generate a data set called dsPhone1.
Step 5: Add three labels, with a bold font, called lblHome, lblWork, and lblMobile, with their Text properties set to Home, Work, and Mobile, respectively.
Step 6: Add three text boxes, below the labels, with a blank Text field named txtHome, txtWork, and txtMobile.
Step 7: Set the DataBindings Text property to DsPhone1 - PhoneNumbers.HomePhone, DsPhone1 - PhoneNumbers.WorkPhone, DsPhone1 - PhoneNumbers.MobilePhone for the text boxes txtHome, txtWork, and txtMobile, respectively.
The Visual Basic .NET Coach
66
Chapter 12 – Advanced TopicsStep 8: The code for linking the Contact form to the Employee form is nearly identical to the code you used for the Financial form:
Private Employee As Integer
Public Property EmployeeID()
Get
'Nothing goes here, no need
End Get
Set(ByVal Value)
Employee = Value
OleDbDataAdapter1.SelectCommand.Parameters(0).Value = Employee
OleDbDataAdapter1.Fill(DsContact1)
End Set
End Property
The Visual Basic .NET Coach
67
Chapter 12 – Advanced TopicsAdding the Final Code to the Employee Information Form
Step 1: Add the following two properties to the form so the forms you create that are referenced from this form can be accessed by the entire form.
Private Financial As frmFinancial
Private Contact As frmContact
Step 2: While the code for calling the additional forms can be coded in the button and menu items’ Click events, it is better to create a separate subroutine for calling each additional form. This way the code does not have to be repeated, and if you had to go back and modify it, the code would only require changing in one place.
Private Sub FinancialForm()
Financial = Nothing
Financial = New frmFinancial()
Financial.EmployeeID = DsEmployee1.Tables(0).Rows(grdEmployees.CurrentRowIndex)(0)
Financial.Show()
End Sub
Private Sub ContactForm()
Contact = New frmContact()
Contact.EmployeeID = DsEmployee1.Tables(0).Rows(grdEmployees.CurrentRowIndex)(0)
Contact.Show()
End Sub
The Visual Basic .NET Coach
68
Chapter 12 – Advanced TopicsStep 3: Now the code for both the button and menu objects’ Click events calling the form are just a call to the subroutine created in Step 2.
Private Sub btnPayroll_Click(...
FinancialForm()
End Sub
Private Sub btnPhone_Click(...
ContactForm()
End Sub
Private Sub mnuWindowFinancial_Click(...
FinancialForm()
End Sub
Private Sub mnuWindowPhone_Click(...
ContactForm()
End Sub