VB Lecture Notes - Methods
Objective #1: Use a call statement to execute a method from another method.
' computes the cost of purchasing donuts Private Sub btnCompute_Click(sender As System.Object, e As System.EventArgs) Handles btnCompute.Click ' *********************** declaration statements ******* Dim numDonuts As Integer = 0 ' # of donuts purchased Dim totalCost As Double = 0 ' total cost of purchases Const PRICE_PER_DONUT As Double = 0.75 ' price per donut Const TAX_RATE As Double = 1.06 ' PA state sales tax ' ********************* obtain user input ************** numDonuts = Val(txtDonuts.Text) ' ********************** calculations ****************** totalCost = numDonuts * PRICE_PER_DONUT * TAX_RATE ' ********************** display the output ************ lblTotalCost.Text = "$" + Str(totalCost)and a Clear button that clears a textbox such as
Call btnClear_Click(sender, e) End Sub
Private Sub btnClear_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClear.Click txtDonuts.Clear() End Subyou can use the statement Call btnClear_Click(sender, e) to execute the btnClear_Click method
Objective #2: Create your own method that is not tied to an event.
Public Class Form1
Dim playerX As Integer = 10 ' horizontal position of player Dim playerY As Integer = 10 ' vertical position of player
' draws graphics on screen
Private Sub Form1_Paint(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles Me.Paint DrawPlayer(sender, e) DrawEnemy(sender, e) End Sub
' draws player
Private Sub DrawPlayer(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs) e.Graphics.DrawLine(Pens.Black, playerX, playerY, playerX, playerY + 100) End Sub
' draws enemy
Private Sub DrawEnemy(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs) e.Graphics.DrawLine(Pens.Red, 200, 50, 200, 150) End Sub
' moves players
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click MoveDiagonal() Me.Refresh() End Sub
' moves player right 10 pixels
Private Sub MoveRight() playerX += 10 End Sub
' moves player down 10 pixels
Private Sub MoveDown() playerY += 10 End Sub
' moves player diagonally down and to the right
Private Sub MoveDiagonal() MoveRight() MoveDown() End Sub
End Class
Objective #3: Explain the benefits of using methods.
Objective #4: Organize the code in your code window.