Developing Microsoft .Net Applications for Windows (Visual Basic .Net) Class 5
description
Transcript of Developing Microsoft .Net Applications for Windows (Visual Basic .Net) Class 5
1COMP3100E
Developing Microsoft .Net
Applications for Windows (Visual
Basic .Net)Class 5
COMP3100E
2COMP3100E
Objectives
Learn to write code to call a procedure & to create a procedure
Learn about Subroutines Learn about Functions Local and Global Variables Introduction to Arrays
3COMP3100E
Procedures
A block of Visual Basic statements enclosed by a declaration statement and an End statement. – All Visual Basic code is written within
procedures. A procedure is invoked from some
other place in the code. When it is finished executing, it
returns control to the code that invoked it; this code is known as the calling code.
The calling code is a statement, or an expression within a statement, that specifies the procedure by name and transfers control to it.
4COMP3100E
Types of Procedures
Visual Basic uses several types of procedures:
Sub procedures– perform actions but do not return a
value to the calling code. (Straight from Microsoft)
– Event-handling procedures are Sub procedures that execute in response to an event triggered by user action or by an occurrence in a program.
Function procedures– return a value to the calling code.
Property procedures – return and assign values of properties
on objects or modules.
5COMP3100E
Procedures and Structured Code
Every line of code in your application must be inside some procedure, such as Main, Calculate, or Button1_Click.
If you subdivide large procedures into smaller ones, your application is more readable.
Procedures are useful for – performing repeated or shared tasks
» such as frequently used calculations, text and control manipulation, and database operations.
– Being invoked from many different places in your code
» so you can use procedures as building blocks for your application.
Structuring your code with procedures gives you the following benefits: – Procedures allow you to break your programs
into discrete logical units. » You can debug separate units more easily than
you can an entire program without procedures. – You can use procedures developed for one
program in other programs, often with little or no modification.
6COMP3100E
SubroutineExample
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim X As Integer Dim Y As Integer
X = Val(TxtX.Text) Y = Val(TxtY.Text) Multiply(X, Y)End Sub
Sub Multiply (ByVal X As Integer, ByVal Y As Integer)
LblResult.Text = Str(X * Y)End Sub
7COMP3100E
The Header
Multiply (ByVal X As Integer, ByVal Y As Integer)
Procedure Name Argument List
– ByVal (By Value)» Indicates that the procedure cannot
replace or reassign the underlying variable element in the calling code.
» ByVal is the default in Visual Basic.
– ByRef (By Reference)» Indicates that the procedure can
modify the underlying variable in the calling code the same way the calling
– Name of Variable– Variable data type
8COMP3100E
Subroutine Example 2
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim X As Integer
Dim Y As Integer
Dim Z As Integer
X = Val(TxtX.Text)
Y = Val(TxtY.Text)
Multiply(X, Y, Z)
LblResult.Text = Str(Z)End Sub
Sub Multiply(ByVal X As Integer, ByVal Y As Integer, ByRef Z As Integer)
Z = X * YEnd Sub
9COMP3100E
Another Subroutine
Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click
'Display the sum of two numbersDim num1, num2 As Double
lstResult.Items.Clear()
ExplainPurpose()
lstResult.Items.Add("")
num1 = 2
num2 = 3
lstResult.Items.Add("The sum of " & num1 & " and " _
& num2 & " is " & num1 + num2 & ".")
End Sub
Sub ExplainPurpose()
REM Explain the task performed by the program
lstResult.Items.Add("This program displays a sentence")
lstResult.Items.Add("identifying two numbers and their sum.")
End Sub
10COMP3100E
Another Subroutine #2
Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click
'Display the sum of two numbers lstResult.Items.Clear() ExplainPurpose() lstResult.Items.Add("") Sum(2, 3)End Sub
Sub Sum(ByVal num1 As Double, ByVal num2 As Double)
'Display numbers and their sumlstResult.Items.Add("The sum of " & num1 & " and " _ & num2 & " is " & (num1 + num2) & ".") End Sub
Sub ExplainPurpose()'Explain the task performed by the programlstResult.Items.Add("This program displays a
sentence")lstResult.Items.Add("identifying two numbers and
their sum.") End Sub
11COMP3100E
Example of Structure
Private Sub btnCompute_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCompute.Click
'This program requests two numbers and
'displays the two numbers and their sum.
Dim x As Double 'First number
Dim y As Double 'Second number
Dim t As Double 'Total
GetNumbers(x, y)
CalculateSum(x, y, t)
DisplayResult(x, y, t)End Sub
Sub GetNumbers(ByRef num1 As Double, ByRef num2 As Double)
'Retrieve the two numbers in the text boxes
num1 = CDbl(txtFirstNum.Text)
num2 = CDbl(txtSecondNum.Text)
End Sub
Sub CalculateSum(ByVal num1 As Double, ByVal num2 As Double, _
ByRef total As Double)
'Add the values of num1 and num2
total = num1 + num2End Sub
Sub DisplayResult(ByVal num1 As Double, ByVal num2 As Double, _
ByVal total As Double)
txtResult.Text = "The sum of " & num1 & " and " & num2 _
& " is " & total & "."End Sub
12COMP3100E
Option Explicit
Visual Basic .NET generally allows implicit conversions of any data type to any other data type. Data loss can occur when the value of one data type is converted to a data type with less precision or smaller capacity, however, a run-time error message will occur if data will be lost in such a conversion. – Option Strict ensures compile-time
notification of these types of conversions so they may be avoided.
In addition to the conditions described above, Option Strict generates an error for: – Any undeclared variable since it is
implied that Option Strict also means Option Explicit.
13COMP3100E
Option Strict ON
Option Strict On
Public Class Form1 Inherits System.Windows.Forms.Form
Private Sub btnConvert_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnConvert.Click
Dim FahrenheitTemp, CelsiusTemp As Double
FahrenheitTemp = CDbl(txtTempF.Text) CelsiusTemp = FtoC(FahrenheitTemp) txtTempC.Text = CStr(CelsiusTemp)Note: The above four lines can be replaced with the
single line'txtTempC.Text = CStr(FtoC(CDbl(txtTempF.Text)))End Sub
Function FtoC(ByVal t As Double) As Double 'Convert Fahrenheit temperature to Celsius Return (5 / 9) * (t - 32)End Function
End Class
14COMP3100E
Local Variables
Private Sub btnDisplay_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDisplay.Click
'Demonstrate the local nature of variables
Dim x As Double = 2
lstResults.Items.Clear()
lstResults.Items.Add(x)
Trivial()
lstResults.Items.Add(x)
Trivial()
lstResults.Items.Add(x)
End Sub
Sub Trivial()
'Do something trivial
Dim x As Double
lstResults.Items.Add(x)
x = 3
lstResults.Items.Add(x)
End Sub
15COMP3100E
Global Variables
Dim num1, num2 As Double 'Class-level variables
Private Sub btnDisplay_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDisplay.Click
'Display the sum of two numbers
num1 = 2
num2 = 3
lstResults.Items.Clear()
AddAndIncrement()
lstResults.Items.Add("")
lstResults.Items.Add("num1 = " & num1)
lstResults.Items.Add("num2 = " & num2)
End Sub
Sub AddAndIncrement()
'Display numbers and their sum
lstResults.Items.Add("The sum of " & num1 & " and " & _
num2 & " is " & (num1 + num2) & ".")
num1 += 1 'Add 1 to the value of num1
num2 += 1 'Add 1 to the value of num2
End Sub
16COMP3100E
Intializing Values
Option Strict On
Public Class Form1 Inherits System.Windows.Forms.Form
+Windows Form Designer Generated Code
Dim pi As Double = 3.14159
Private Sub btnCompute_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCompute.Click
'Display the area of a circle of radius 5 txtArea.Text = "The area of a circle of radius 5 is " & (pi * 5
* 5) End Sub
End Class
17COMP3100E
Function
Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click
Dim X As Integer Dim Y As Integer Dim Z As Integer
X = Val(TxtX.Text) Y = Val(TxtY.Text)
LblResult.Text = Multiply(X, Y)End Sub
Sub Multiply(ByVal X As Integer, ByVal Y As Integer, _ ByRef Z As Integer) Z = X * YEnd Sub
Function multiply(ByVal x As Integer, ByVal y As Integer) As Integer Return (x * y)End Function
18COMP3100E
Function Calls
Private Sub btnConvert_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnConvert.Click
Dim FahrenheitTemp, CelsiusTemp As Double
FahrenheitTemp = CDbl(txtTempF.Text)
CelsiusTemp = FtoC(FahrenheitTemp)
txtTempC.Text = CStr(CelsiusTemp)
Note: The above four lines can be replaced with the single line
'txtTempC.Text = CStr(FtoC(CDbl(txtTempF.Text)))
End Sub
Function FtoC(ByVal t As Double) As Double
'Convert Fahrenheit temperature to Celsius
Return (5 / 9) * (t - 32)
End Function
19COMP3100E
Function Example #2
Private Sub btnDetermine_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDetermine.Click
'Determine a person's first name
Dim name As String
name = txtFullName.Text
txtFirstname.Text = FirstName(name)
End Sub
Function FirstName(ByVal name As String) As String
'Extract the first name from a full name
Dim firstSpace As Integer
firstSpace = name.IndexOf(" ")
Return name.Substring(0, firstSpace)
End Function
20COMP3100E
Function Example #3
Private Sub btnCalculate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCalculate.Click
'Calculate the length of the hypotenuse of a right
'triangle
Dim a, b As Double
a = CDbl(txtSideOne.Text)
b = CDbl(txtSideTwo.Text)
txtHyp.Text = CStr(Hypotenuse(a, b))
End Sub
Function Hypotenuse(ByVal a As Double, _
ByVal b As Double) As Double
'Calculate the hypotenuse of a right triangle
'having sides of lengths a and b
Return Math.Sqrt(a ^ 2 + b ^ 2)
End Function
21COMP3100E
Business Example
Private Sub btnCompute_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCompute.Click
'Find the future value of a bank deposit
Dim p As Double 'principal, the amount deposited Dim r As Double 'annual rate of interest Dim c As Double 'number of times interest is 'compounded per year Dim n As Double 'number of years InputData(p, r, c, n) DisplayBalance(p, r, c, n)End Sub
Sub InputData(ByRef p As Double, ByRef r As Double, _
ByRef c As Double, ByRef n As Double)
'Get the four values from the text boxes p = CDbl(txtAmount.Text) r = CDbl(txtRate.Text) c = CDbl(txtNumComp.Text) n = CDbl(txtNumYrs.Text)End Sub
22COMP3100E
Business Example Continued
Sub DisplayBalance(ByVal p As Double, _ ByVal r As Double, _ ByVal c As Double, _ ByVal n As Double)'Display the balance in a text box
Dim balance As Double balance = FutureValue(p, r, c, n) txtbalance.Text = FormatCurrency(balance)End Sub
Function FutureValue(ByVal p As Double, _ ByVal r As Double, _ ByVal c As Double, _ ByVal n As Double) As Double'Find the future value of a bank savings account'p principal, the amount deposited'r annual rate of interest'c number of times interest is compounded per year'n number of years Dim i As Double 'interest rate per period Dim m As Double 'total number of times interest 'is compounded i = r / c m = c * n Return p * ((1 + i) ^ m) End Function
23COMP3100E
What are arrays?
Arrays allow you to refer to a series of variables by the same name and to use a number, called an index or subscript, to tell them apart. – This helps you create shorter and simpler code in
many situations, because you can set up loops that deal efficiently with any number of elements by using the index number.
Every dimension of an array has a nonzero length. The elements of the array are contiguous along each dimension from subscript 0 through the highest subscript of that dimension. – Because Visual Basic allocates space for an array
element corresponding to each index number, you should avoid declaring any dimension of an array larger than necessary.
– Arrays do not have fixed size in Visual Basic. You can change the size of an array after you have created it. The ReDim statement assigns a completely new array object to the specified array variable. Therefore, ReDim can change the length of each dimension.
Simple Arrays contain values of only 1 data type
24COMP3100E
Creating Arrays
Dim monthNames(11) as string– monthNames(0) = "January"– monthNames(1) = "February"– monthNames(2) = "March"– monthNames(3) = "April"– monthNames(4) = "May"– monthNames(5) = "June"– monthNames(6) = "July"– monthNames(7) = "August"– monthNames(8) = "September"– monthNames(9) = "October“– monthNames(10) = “November”– monthNames(11) = “December”
25COMP3100E
Using Arrays
Dim monthNum As Integer
Rem Display month name
Picture1.Cls
monthNum =Val(InputBox ("Enter month number:"))
txtMonthName.Text = “Month name is “ & _ monthNames(monthNum)
26COMP3100E
Using Arrays (Your teacher)
Dim teamName(3) As String
Private Sub btnWhoWon_Click(ByVal sender As _ System.Object, ByVal e As _ System.EventArgs) _ Handles btnWhoWon.Click
Dim n As Integer n = CInt(txtNumber.Text) txtWinner.Text = teamName(n -1)End Sub
Private Sub Form1_Load(ByVal sender As _ System.Object, ByVal e As System.EventArgs) _ Handles MyBase.Load
'Place Super Bowl Winners into the array teamName(0) = "Packers" teamName(1) = "Packers" teamName(2) = "Jets" teamName(3) = "Chiefs"End Sub
27COMP3100E
Simple Swap
Private Sub btnAlphabetize_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAlphabetize.Click
'Alphabetize two words
Dim firstWord, secondWord, temp As String
firstWord = txtFirstWord.Text
secondWord = txtSecondWord.Text
If (firstWord > secondWord) Then 'Swap the two words
temp = firstWord
firstWord = secondWord
secondWord = temp
End If
txtResult.Text = firstWord & " before " & secondWord
End Sub
28COMP3100E
Using Array.Sort
Public Class Form1 Dim RandArray(0 To 499) As Long
'Initialize the Progress bar object and display num of elements
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
ProgressBar1.Minimum = 0 ProgressBar1.Maximum = UBound(RandArray) Label2.Text = UBound(RandArray) + 1End Sub
'Fill the array with random numbers and display in text box
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim i As Integer For i = 0 To UBound(RandArray) RandArray(i) = Int(Rnd() * 1000000) TextBox1.Text = TextBox1.Text & RandArray(i) &
vbCrLf ProgressBar1.Value = i 'move progress bar Next iEnd Sub
29COMP3100E
Array.sort continued
'Sort the array using the Array.Sort method and display
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim i As Integer TextBox1.Text = "" Array.Sort(RandArray) For i = 0 To UBound(RandArray) TextBox1.Text = TextBox1.Text & RandArray(i) &
vbCrLf ProgressBar1.Value = i 'move progress bar Next iEnd Sub
'Reverse the order of array elements using Array.Reverse
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
Dim i As Integer TextBox1.Text = "" Array.Reverse(RandArray) For i = 0 To UBound(RandArray) TextBox1.Text = TextBox1.Text & RandArray(i) &
vbCrLf ProgressBar1.Value = i 'move progress bar Next iEnd Sub End Class
30COMP3100E
Bubble Sort
Dim person() As String = _ {"Pebbles", "Barney", "Wilma", "Fred", "Dino"}
Private Sub Form1_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load
'Display unsorted list Dim i As Integer For i = 0 To 4 lstPeople.Items.Add(person(i)) Next iEnd Sub
Private Sub btnSort_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnSort.Click
‘Bubble sort names Dim passNum, i As Integer, temp As String Dim Done As Boolean passNum = 1 Do Done = True For i = 0 To 4 - passNum If (person(i) > person(i + 1)) Then Done = False temp = person(i) person(i) = person(i + 1) person(i + 1) = temp End If Next i passNum = passNum + 1 Loop While (Not Done) lstPeople.Items.Clear() For i = 0 To 4 lstPeople.Items.Add(person(i)) Next End Sub
31COMP3100E
Shell Sort
Dim part(50) As String
Dim numParts As Integer
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'Read names of parts
numParts = 0 'Number of parts
Dim sr As IO.StreamReader = IO.File.OpenText("SHOEPART.TXT")
Do While (sr.Peek <> -1) And (numParts < part.GetUpperBound(0))
numParts += 1
part(numParts) = sr.ReadLine
Loop
sr.Close()
End Sub
Private Sub btnDisplay_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDisplay.Click
'Sort and display parts of running shoe
SortData()
ShowData()
End Sub
32COMP3100E
Shell Sort
Sub SortData()'Shell sort shoe parts Dim gap As Integer, doneFlag As Boolean Dim index As Integer, temp As String
gap = CInt(numParts / 2) Do While (gap >= 1) Do done = True For index = 1 To numParts - gap If (part(index) > part(index + gap)) Then temp = part(index) part(index) = part(index + gap) part(index + gap) = temp done = False End If Next index Loop while (not done) gap = CInt(gap / 2) LoopEnd Sub
33COMP3100E
Fixed Arrays
Public Class Form1Dim Temperatures(0 To 6) As Single
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
End SubPrivate Sub Button1_Click(ByVal sender As
System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim Prompt, Title As String Dim i As Short Prompt = "Enter the day’s high temperature." For i = 0 To UBound(Temperatures) Title = "Day " & (i + 1) Temperatures(i) = InputBox(Prompt, Title) NextEnd Sub
34COMP3100E
Fixed Arrays Continued
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim Result As String Dim i As Short Dim Total As Single = 0 Result = "High temperatures for the
week:" & vbCrLf & vbCrLf For i = 0 To UBound(Temperatures) Result = Result & "Day " & _
(i + 1) & vbTab & _ Temperatures(i) & vbCrLf Total = Total + Temperatures(i) Next Result = Result & vbCrLf & _ "Average temperature: " & _
Format(Total / 7, "0.0") TextBox1.Text = ResultEnd SubEnd Class
35COMP3100E
Dynamic Arrays
Public Class Form1 Dim Temperatures() As Single Dim Days As Integer
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
End SubPrivate Sub Button1_Click(ByVal sender As
System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim Prompt, Title As String Dim i As Short Prompt = "Enter the day’s high temperature." Days = InputBox("How many days?", "Create Array") If Days > 0 Then ReDim Temperatures(Days - 1) For i = 0 To UBound(Temperatures) Title = "Day " & (i + 1) Temperatures(i) = InputBox(Prompt, Title) NextEnd Sub
36COMP3100E
Dynamic Arrays Continued
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim Result As String Dim i As Short Dim Total As Single = 0 Result = "High temperatures:" & _ vbCrLf & vbCrLf For i = 0 To UBound(Temperatures) Result = Result & "Day " & (i + 1) & vbTab & _ Temperatures(i) & vbCrLf Total = Total + Temperatures(i) Next Result = Result & vbCrLf & _ "Average temperature: " & _ Format(Total / Days, "0.0") TextBox1.Text = ResultEnd SubEnd Class