Post on 18-Dec-2015
1
Lesson 11 — Building and Using A User Control
Microsoft Visual Basic .NET, Introduction to Programming
2
Objectives
Build a new user control. Access the properties of a user control. Test the user control in an application. Make a user control available to other
applications. Enhance an existing control and package it
as a new user control. Create a custom user-drawn control.
3
Vocabulary
Dynamic link library (DLL) Inheritance Picker System.Drawing User control
4
Building User Controls
You can build your own user controls in one of three ways:
Combine existing controls and write code that binds them together.
Enhance an existing control to give it new functionality.
Draw an original control to provide a new user interface.
5
LoanCalculator Control
This control collects the loan balance, yearly interest rate, and the number of years of the loan and then calculates and displays the monthly payment. Once data are entered, the monthly payment, as well as the total amount paid back during the life of the loan and the finance charge, are also available as properties of the control.
6
Programming Skills
Check your output. After completing a program, check program output by hand, or at least estimate the result in your head or on paper to confirm that the program is displaying correct output. More than one contractor has been burned by spreadsheet estimates for jobs where the spreadsheet formulas were incorrectly entered, resulting in a bid that could not even cover expenses. It is embarrassing to hand over a defective product to the user.
7
The Add New Item dialog Box, Showing the Addition of a New User Control
8
Layout of Controls on the LoanCalculator User Control
9
Step-by-Step 11.1
Public Balance As Decimal
Public Rate As Double
Public Years As Integer
Public Pmt As Decimal
Public TotalPayback As Decimal
Public FinanceCharge As Decimal
10
Step-by-Step 11.1
Dim MRate As Double 'Monthly Interest Rate
Dim Payments As Integer 'Total Number of Payment Balance = CDec(txtBalance.Text)
Rate = CDbl(txtRate.Text)
Years = CInt(txtYears.Text)
If Balance = 0 Or Rate = 0 Or Years = 0 Then
Exit Sub
End If
11
Step-by-Step 11.1
MRate = Rate / 1200
Payments = Years * 12
Pmt = Balance * MRate / (1 - (1 + MRate) ^
(-Payments))
TotalPayback = Pmt * Payments
FinanceCharge = TotalPayback - Balance
lblPmt.Text = Format(Pmt, "Currency")
12
The LoanCalculator Control at the Bottom of the Toolbox
13
Note
If a user control is flawed, open the control’s Designer to make changes and then rebuild the control. Until the control is rebuilt, the changes made to the control will not take affect.
14
Accessing Properties of the User Control
You access the properties of a user control in the same way you access the properties of an object created with a class definition. The simplest way to create a property in a class definition is to use a Public statement to declare a variable. The user control is really a class definition, so the rules for creating properties in a user control are the same as the rules for creating properties in a class definition.
15
Final Placement of Controls for the LoanCalculator Application
16
Step-by-Step 11.2
MessageBox.Show("The Total of the Payments is " & _
Format(LoanCalculator1.TotalPayback, "Currency"))
MessageBox.Show("The Total Finance charge is " & _
Format(LoanCalculator1.FinanceCharge, "Currency"))
17
The Object Browser Showing the LoanCalculator Object
18
Declaring Variables
Public properties of a user control (that is, properties available for use by the application in which the user control is used), can be declared as variables in the Declarations section with the keyword Public. Variables declared with the keyword Dim are not public and, therefore, not available to an application. Variables declared within an event procedure in the user control are not visible, but locked. Like variables declared with Dim in the Declarations section, they are completely invisible to the application.
19
Making a User Control Available to Other Applications
To build user controls that you can use in multiple applications, you must add the user controls to a Windows Control Library project.
20
Windows Control Library Selected in the Templates Pane of the New Project DialogBox
21
The CircleArea User Control Showing Placement of Controls
22
Step-by-Step 11.3
Public Radius, Area, Circumference As Double Try Radius = CDbl(txtRadius.Text) Catch When Radius = 0 MessageBox.Show("The radius is 0, please reenter.") Exit Sub Catch When Radius < 0 MessageBox.Show("The radius is negative, please
reenter.") Exit Sub End Try Area = Math.PI * Radius ^ 2 Circumference = 2 * Math.PI * Radius lblArea.Text = Format(Area, "#,##0.######")
23
Error Message Received When You Try to Execute a Windows Control Library Project
24
Programming Skills
A great way to debug a program is to explain it to someone else. Formal “walkthroughs” are often used in industry to discover program bugs. Explaining program code to your peers helps you focus on problems and discover logical errors that you did not expect existed. Print out code to review it. Often, mistakes overlooked on a computer monitor jump out at you when you look at a printout.
25
Historically Speaking
In 1964, professors John G. Kemeny and Thomas E. Kurtz of Dartmouth University designed a programming language for incoming computer students: Beginners All-purpose Symbolic Instruction Code or BASIC. Eleven years later in 1975, Paul Allen and Bill Gates wrote a version of BASIC for the MITS Altair 8800 computer with 4K memory. Programmers at Microsoft, the company founded by Gates and Allen, went on to write several versions of BASIC for many different microcomputers. Gates himself participated in many of the early projects.
26
Projects Tab in the Add Reference Dialog Box
27
Note
Depending on your screen resolution, you may want more room on the screen to see the Code window. When you are not adding controls to a form or user control, close the Toolbox by clicking its Close button. Restore the Toolbox by clicking its button on the toolbar. The Toolbox button has a crossed wrench and hammer on it.
28
Adding to an Existing Control
Another way to create a unique user control is to add new functions to an existing control. In this section you modify the LoanCalculator control that you defined earlier in this lesson to display a simple amortization table. The modified control inherits all the functions of the original control.
29
Programming Skills
Do you know everything you need to know to write the programs required for your job? Read the on‑line documentation. Read publications dedicated to Visual Basic or Visual Studio. You will probably find program features and code that solve problems in different or better ways. Visual Basic is a large language. Chances are there is something more you can learn to improve programming skills.
30
Historically Speaking
In 1979, Dan Bricklin and Bon Frankston designed and wrote the first electronic spreadsheet program, Visicalc. They purposely did not seek patent protection for their creation. This act greatly stimulated the computer industry because it turned out that the spreadsheet was a wonderful tool for many different disciplines. Many other companies came out with their own similar products. Lotus bought the rights to Visicalc in 1985. Shortly after that, the product disappeared.
31
Adding the LoanCalculator Control to the FinancialLibrary Project
32
Adding the FinancialLibrary to the ModifiedLoanControl Project
33
Inheritance Picker Dialog Box
34
The ModifiedLoanCalculator Control in the Designer
35
Step-by-Step 11.6
Dim CurrentBalance As Decimal = Me.Balance
Dim TotalPayments As Integer = Me.Payments
Dim YearlyInterestRate As Double = Me.Rate
Dim MonthlyPayment As Decimal = Me.Pmt
Dim PaymentNumber As Integer
Dim MonthlyInterestRate As Double = YearlyInterestRate / 1200
Dim MonthlyInterest As Double = 0
36
Step-by-Step 11.6
For PaymentNumber = 1 To TotalPayments MonthlyInterest = CurrentBalance * MonthlyInterestRate CurrentBalance = CurrentBalance + MonthlyInterest -
MonthlyPayment lstAmortizationTable.Items.Add(PaymentNumber & _ vbTab & Format(MonthlyInterest, "Currency") & _ vbTab & Format(CurrentBalance, "Currency")) Next
37
The ModifiedLoanCalculator Control in an Application
38
Building a Custom Interface User Control
A user-drawn control lets the programmer define the look of the user interface.
The biggest difference between a user-drawn control and a regular user control is that the user-drawn control uses no standard parts out of the Toolbox; that is, it contains no text boxes, labels, or buttons. The control’s Paint event procedure builds the visual appearance of the control by using the graphics methods found in System.Drawing.
System.Drawing is a library of classes used to draw graphic images and create graphic objects.
39
Step-by-Step 11.7
Dim myFont As System.Drawing.Font = _ New System.Drawing.Font("Arial", 20,
FontStyle.Bold) Dim MyFrameColor As Color = Color.DarkCyan Dim MyBodyColor As Color =
Color.BlanchedAlmond Public TextColor As Color = Color.MistyRose Dim MyFrameWidth As Integer = 30 Dim MyText As String = "Very Pretty Eyes"
40
Step-by-Step 11.7
' Declares and instantiates a drawing pen.Dim myPen As System.Drawing.Pen = New
System.Drawing.Pen(MyFrameColor, 30)' Declares and instantiates a SolidBrush Dim myBrush As System.Drawing.SolidBrush = New
System.Drawing.SolidBrush(TextColor)e.Graphics.DrawRectangle(myPen, e.ClipRectangle)e.Graphics.DrawString(MyText, myFont, myBrush,
20, 30)Me.BackColor = MyBodyColor
41
Step-by-Step 11.7
ResizeRedraw = True
Public Property FrameColor() As ColorGet FrameColor = MyFrameColorEnd GetSet(ByVal Value As Color) MyFrameColor = Value Me.Refresh()End SetEnd Property
42
Step-by-Step 11.7
Public Property pfFont() As FontGet pfFont = myFontEnd GetSet(ByVal Value As Font) myFont = Value Me.Refresh()End SetEnd Property
43
Step-by-Step 11.7
Public Property BodyColor() As ColorGet BodyColor = MyBodyColorEnd GetSet(ByVal Value As Color) MyBodyColor = Value Me.Refresh()End SetEnd Property
44
Step-by-Step 11.7
Public Property pfText() As StringGet pfText = MyTextEnd GetSet(ByVal Value As String) If Len(Value) = 0 Then MyText = "" Else MyText = Value End If Me.Refresh()End SetEnd Property
45
Step-by-Step 11.7
Add a button to the form. Change the name of the button to btnChangeFont. Change the Text property of the button to Change Font. Resize the button to display the entire text. Add a FontDialog control to the form. Double-click btnChangeFont to open the button’s Click event handler. Add the following code:
FontDialog1.ShowDialog()
PictureFrame1.pfFont = FontDialog1.Font
46
Historically Speaking
Steve Jobs is partly responsible for Visual Basic. Well, not directly. Steve Jobs and Steve Wozniak started the Apple computer company in a garage in the mid 1970s. In 1979, Jobs visited the Xerox Palo Alto Research Center, PARC, and saw the Alto computer. It had a mouse and a graphical user interface. Jobs instantly recognized the future of computing in the graphical user interface. The Lisa computer, introduced a few years later, was the first imperfect version of this future. The Macintosh computer, presented in 1984, was far more successful and refined. The graphical user interface is now the standard of the industry, and Visual Basic is the fastest and easiest way to deliver programs with that graphical user interface to customers.
47
Summary
User controls are a good way to pack commonly used functions and procedures into a portable package.
You can build your own user controls in one of three ways: by combining existing controls and writing code that binds them together; by enhancing an existing control to give it new functionality; or by drawing an original control to provide a new user interface. All three require program code to make the functionality of the control available to the programmer.
A user control has two run‑time behaviors: one when the control is put on an application form, and another when the application containing the control is running.
48
Summary
The rules for accessing properties of a user control are the same as the rules for accessing properties for a class definition. Public properties of a user control, that is, properties available for use by the application in which the user control is used, can be declared in the Declarations section with the keyword Public.
To compile a user control so that it may be used in an application, select Build | Build Solution on the menu bar. Once compiled, a user control may be added to an application.
49
Summary
To build user controls that you can use in multiple applications, you must add the user controls to a Windows Control Library project.
System.Drawing is a library of classes used to draw graphic images and create graphic objects.
A user-drawn control lets you design a custom interface for a new user control at the cost of having to provide code to draw every line, fill every space with color, and draw each character of text on the face of the control.