Functions & Procedures
Functions & Procedures
Functions & Procedures
Net - Functions
A procedure is a group of statements that together perform a task when called. After the procedure
is executed, the control returns to the statement calling the procedure. VB.Net has two types of
procedures:
Functions
Defining a Function
The Function statement is used to declare the name, parameter and the body of a function. The
syntax for the Function statement is:
[Modifiers] Function FunctionName [(ParameterList)] As ReturnType
[Statements]
End Function
Where,
Modifiers: specify the access level of the function; possible values are: Public, Private,
Protected, Friend, Protected Friend and information regarding overloading, overriding,
sharing, and shadowing.
ReturnType: specifies the data type of the variable the function returns
Example
Following code snippet shows a function FindMax that takes two integer values and returns the
larger of the two.
Where,
Modifiers: specify the access level of the procedure; possible values are: Public, Private,
Protected, Friend, Protected Friend and information regarding overloading, overriding,
sharing, and shadowing.
Example
The
following
example
demonstrates
Sub
takes
two
parameters hours and wages and displays the total pay of an employee:
Module mysub
Sub CalculatePay(ByVal hours As Double, ByVal wage As Decimal)
'local variable declaration
Dim pay As Double
pay = hours * wage
Console.WriteLine("Total Pay: {0:C}", pay)
End Sub
Sub Main()
'calling the CalculatePay Sub Procedure
CalculatePay(25, 10)
CalculatePay(40, 20)
CalculatePay(30, 27.5)
Console.ReadLine()
End Sub
End Module
When the above code is compiled and executed, it produces the following result:
Total Pay: $250.00
Total Pay: $800.00
Total Pay: $825.00
In VB.Net, you declare the reference parameters using the ByVal keyword. The following example
demonstrates the concept:
Module paramByval
Sub swap(ByVal x As Integer, ByVal y As Integer)
Dim temp As Integer
temp = x ' save the value of x
x=y
When the above code is compiled and executed, it produces the following result:
Before swap, value of a :100
Before swap, value of b :200
After swap, value of a :100
After swap, value of b :200
It shows that there is no change in the values though they had been changed inside the function.
When the above code is compiled and executed, it produces the following result:
Before swap, value of a : 100
Mouse events
Keyboard events
MouseHover - it occurs when the mouse pointer hovers over the control
MouseMove - it occurs when the mouse pointer moves over the control
MouseUp - it occurs when the mouse pointer is over the control and the mouse button is
released
MouseWheel - it occurs when the mouse wheel moves and the control has focus
The event handlers of the mouse events get an argument of typeMouseEventArgs. The
MouseEventArgs object is used for handling mouse events. It has the following properties:
Example
Following is an example, which shows how to handle mouse events. Take the following steps:
Add three labels, three text boxes and a button control in the form.
Change the text properties of the labels to - Customer ID, Name and Address, respectively.
Change the name properties of the text boxes to txtID, txtName and txtAddress,
respectively.
End Sub
Private Sub txtID_MouseLeave(sender As Object, e As EventArgs) _
Handles txtID.MouseLeave
'code for handling mouse leave on ID textbox
txtID.BackColor = Color.White
txtID.ForeColor = Color.Blue
End Sub
Private Sub txtName_MouseEnter(sender As Object, e As EventArgs) _
Handles txtName.MouseEnter
'code for handling mouse enter on Name textbox
txtName.BackColor = Color.CornflowerBlue
txtName.ForeColor = Color.White
End Sub
Private Sub txtName_MouseLeave(sender As Object, e As EventArgs) _
Handles txtName.MouseLeave
'code for handling mouse leave on Name textbox
txtName.BackColor = Color.White
txtName.ForeColor = Color.Blue
End Sub
Private Sub txtAddress_MouseEnter(sender As Object, e As EventArgs) _
Handles txtAddress.MouseEnter
'code for handling mouse enter on Address textbox
txtAddress.BackColor = Color.CornflowerBlue
txtAddress.ForeColor = Color.White
End Sub
Private Sub txtAddress_MouseLeave(sender As Object, e As EventArgs) _
Handles txtAddress.MouseLeave
'code for handling mouse leave on Address textbox
txtAddress.BackColor = Color.White
txtAddress.ForeColor = Color.Blue
End Sub
Handles Button1.Click
MsgBox("Thank you " & txtName.Text & ", for your kind cooperation")
End Sub
End Class
When the above code is executed and run using Start button available at the Microsoft Visual
Studio tool bar, it will show the following window:
Try to enter text in the text boxes and check the mouse events:
Following are the various keyboard events related with a Control class:
KeyDown - occurs when a key is pressed down and the control has focus
KeyPress - occurs when a key is pressed and the control has focus
KeyUp - occurs when a key is released while the control has focus
The event handlers of the KeyDown and KeyUp events get an argument of type KeyEventArgs.
This object has the following properties:
Modifiers - it indicates which modifier keys (Ctrl, Shift, and/or Alt) are pressed
The event handlers of the KeyDown and KeyUp events get an argument of type KeyEventArgs.
This object has the following properties:
Example
Let us continue with the previous example to show how to handle keyboard events. The code will
verify that the user enters some numbers for his customer ID and age.
Add a label with text Property as 'Age' and add a corresponding text box named txtAge.
Add the following codes for handling the KeyUP events of the text box txtID.
Handles txtID.KeyUp
End If
End Sub
Add the following codes for handling the KeyUP events of the text box txtID.
Handles txtAge.KeyUp
End If
End Sub
When the above code is executed and run using Start button available at the Microsoft Visual
Studio tool bar, it will show the following window:
If you leave the text for age or ID as blank or enter some non-numeric data, it gives a warning
message box and clears the respective text:
Try: A Try block identifies a block of code for which particular exceptions will be activated.
It's followed by one or more Catch blocks.
Catch: A program catches an exception with an exception handler at the place in a program
where you want to handle the problem. The Catch keyword indicates the catching of an
exception.
Finally: The Finally block is used to execute a given set of statements, whether an
exception is thrown or not thrown. For example, if you open a file, it must be closed whether
an exception is raised or not.
Throw: A program throws an exception when a problem shows up. This is done using a
Throw keyword.
Syntax
Assuming a block will raise an exception, a method catches an exception using a combination of
the Try and Catch keywords. A Try/Catch block is placed around the code that might generate an
exception. Code within a Try/Catch block is referred to as protected code, and the syntax for using
Try/Catch looks like the following:
Try
[ tryStatements ]
[ Exit Try ]
[ Catch [ exception [ As type ] ] [ When expression ]
[ catchStatements ]
[ Exit Try ] ]
[ Catch ... ]
[ Finally
[ finallyStatements ] ]
End Try
You can list down multiple catch statements to catch different type of exceptions in case your try
block raises more than one exception in different situations.
Handling Exceptions
VB.Net provides a structured solution to the exception handling problems in the form of try and
catch blocks. Using these blocks the core program statements are separated from the errorhandling statements.
These error handling blocks are implemented using the Try, Catch andFinally keywords. Following
is an example of throwing an exception when dividing by zero condition occurs:
Module exceptionProg
Sub division(ByVal num1 As Integer, ByVal num2 As Integer)
When the above code is compiled and executed, it produces the following result:
Exception caught: System.DivideByZeroException: Attempted to divide by zero.
at ...
Result: 0
VB.NET has a inbuilt class that deals with errors. The Class is called Exception. When an
exception error is found, an Exception object is created. The coding structure VB.NET uses to
deal with such Exceptions is called the Try Catch structure.
In the coding area for your button, type the word Try. Then hit the return key on your keyboard.
VB.NET completes the rest of the structure for you:
Try
Catch ex As Exception
End Try
The Try word means "Try to execute this code". The Catch word means "Catch any errors here".
The ex is a variable, and the type of variable it is is an Exception object.
Move your line of code from the previous section to the Try part:
Try
rt1.LoadFile("C:\test10.txt", RichTextBoxStreamType.PlainText)
Catch ex As Exception
End Try
When you run your programme, VB will Try to execute any code in the Try part. If everything
goes well, then it skips the Catch part. However, if an error occurs, VB.NET jumps straight to
Catch. Add the following to your Catch part:
MessageBox.Show(ex.Message)
Your coding window should look like this:
Because ex is an object variable, it now has its own Properties and methods. One of these is the
Message property. Run your programme and test it out. Click your button. You should see the
following error message:
The message is coming from the "additional Information" section of the error message we saw
earlier, the one we didn't handle. But the point about this new message box is that it will not
crash your programme. You have handled the Exception, and displayed an appropriate message
for the user.
If you know the kind of error that a programme might throw, you can get what Type it is from the
Error message box you saw earlier. This one:
Click the View Details links under Actions to see the following:
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
There is one last part of the Try Catch Statement that VB.NET doesn't add for you - Finally:
Try
Catch ex As Exception
Finally
End Try
The Finally part is always executed, whether an error occurs or not. You typically add a Finally
part to perform any cleanup operations that are needed. For example, you may have opened a file
before going into a Try Catch Statement. If an error occurs, the file will still be open. Whether
an error occurs or not, you still need to close the file. You can do that in the Finally part.
But Microsoft advise that you always use Try Catch Statements in your code. However,
throughout the rest of this course, for convenience sake, we won't be using them much. Even
when we should be.But that's no excuse for you not to use them!
In the next part, we'll take a look at Logic Errors.