Developing Microsoft .Net Applications for Windows (Visual Basic .Net) Class 5

Publish in

Documents

6 views

Please download to get full document.

View again

of 36
All materials on our website are shared by users. If you have any questions about copyright issues, please report us to resolve them. We are always happy to assist you.
Share
Description
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.
Transcript
Developing Microsoft .Net Applications for Windows (Visual Basic .Net)Class 5COMP3100EObjectives
  • 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.
  • SubroutineExamplePrivate 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 SubSub Multiply (ByVal X As Integer, ByVal Y As Integer) LblResult.Text = Str(X * Y)End SubThe HeaderMultiply (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 2Private 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 SubSub Multiply(ByVal X As Integer, ByVal Y As Integer, ByRef Z As Integer) Z = X * YEnd SubAnother SubroutinePrivate 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 DoublelstResult.Items.Clear()ExplainPurpose()lstResult.Items.Add("")num1 = 2num2 = 3lstResult.Items.Add("The sum of " & num1 & " and " _ & num2 & " is " & num1 + num2 & ".")End SubSub ExplainPurpose() REM Explain the task performed by the programlstResult.Items.Add("This program displays a sentence")lstResult.Items.Add("identifying two numbers and their sum.")End SubAnother Subroutine #2Private 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 SubSub 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 SubSub 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 SubExample of StructurePrivate 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 SubSub 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 SubSub CalculateSum(ByVal num1 As Double, ByVal num2 As Double, _ByRef total As Double)'Add the values of num1 and num2 total = num1 + num2End SubSub DisplayResult(ByVal num1 As Double, ByVal num2 As Double, _ ByVal total As Double)txtResult.Text = "The sum of " & num1 & " and " & num2 _ & " is " & total & "."End SubOption 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 ONOption Strict OnPublic Class Form1 Inherits System.Windows.Forms.FormPrivate Sub btnConvert_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnConvert.ClickDim 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 SubFunction FtoC(ByVal t As Double) As Double 'Convert Fahrenheit temperature to Celsius Return (5 / 9) * (t - 32)End FunctionEnd ClassLocal 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 SubGlobal VariablesDim num1, num2 As Double 'Class-level variablesPrivate 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 SubSub AddAndIncrement()'Display numbers and their sumlstResults.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 num2End SubIntializing ValuesOption Strict OnPublic 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 SubEnd ClassFunctionPrivate Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.ClickDim 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 SubSub Multiply(ByVal X As Integer, ByVal Y As Integer, _ ByRef Z As Integer) Z = X * YEnd SubFunction multiply(ByVal x As Integer, ByVal y As Integer) As Integer Return (x * y)End FunctionFunction CallsPrivate Sub btnConvert_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnConvert.ClickDim 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 SubFunction FtoC(ByVal t As Double) As Double'Convert Fahrenheit temperature to Celsius Return (5 / 9) * (t - 32)End FunctionFunction 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 FunctionFunction Example #3Private 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 SubFunction 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 FunctionBusiness ExamplePrivate 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 SubSub 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 SubBusiness Example ContinuedSub 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 SubFunction 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 FunctionWhat 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 ArraysDim monthNum As IntegerRem Display month namePicture1.Cls monthNum =Val(InputBox ("Enter month number:")) txtMonthName.Text = “Month name is “ & _ monthNames(monthNum)Using Arrays (Your teacher)Dim teamName(3) As StringPrivate 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 SubPrivate 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 SubSimple 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 SubUsing Array.SortPublic Class Form1 Dim RandArray(0 To 499) As Long 'Initialize the Progress bar object and display num of elementsPrivate 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 boxPrivate 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 SubArray.sort continued'Sort the array using the Array.Sort method and displayPrivate 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.ReversePrivate 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 ClassBubble 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 SubPrivate 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 SubShell 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 SubShell SortSub 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 SubFixed ArraysPublic Class Form1Dim Temperatures(0 To 6) As SinglePrivate Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.LoadEnd 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 SubFixed Arrays ContinuedPrivate 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 ClassDynamic ArraysPublic Class Form1 Dim Temperatures() As Single Dim Days As IntegerPrivate Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.LoadEnd 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 SubDynamic Arrays ContinuedPrivate 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 Tota
    Related Search
    Related Documents
    View more...
    We Need Your Support
    Thank you for visiting our website and your interest in our free products and services. We are nonprofit website to share and download documents. To the running of this website, we need your help to support us.

    Thanks to everyone for your continued support.

    No, Thanks