360 likes | 508 Views
Developing Microsoft .Net Applications for Windows (Visual Basic .Net) Class 5. COMP3100E. 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. Procedures.
E N D
Developing Microsoft .Net Applications for Windows (Visual Basic .Net)Class 5 COMP3100E
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
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.
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.
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.
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
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
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 * Y End Sub
Another Subroutine Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click 'Display the sum of two numbers Dim 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
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 sum lstResult.Items.Add("The sum of " & num1 & " and " _ & num2 & " is " & (num1 + num2) & ".") End Sub Sub ExplainPurpose() '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
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 + num2 End 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
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.
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
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
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
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
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 * Y End Sub Function multiply(ByVal x As Integer, ByVal y As Integer) As Integer Return (x * y) End Function
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
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
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
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
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
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
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”
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)
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
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
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) + 1 End 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 i End Sub
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 i End 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 i End Sub End Class
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 i End 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
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
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) Loop End Sub
Fixed Arrays Public Class Form1 Dim Temperatures(0 To 6) As Single Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load End Sub Private 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) Next End Sub
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 = Result End Sub End Class
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 Sub Private 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) Next End Sub
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 = Result End Sub End Class