Visual Programming: Session: 4 Selva Kumar S

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 36

Visual Programming

Session: 4 Selva kumar S

Quick Recap
Windows Forms: Text Boxes, Rich Text Boxes, Labels, and Link Labels Button Check box, radio box, panels Picture Boxes Scroll Bars Splitters Track Bars Notify Icons Tool Tips Timers

Sub Procedures and Functions


Procedures are made up of series of Visual Basic statements that, when called, are executed. After the call is finished, control returns to the statement that called the procedure. You can pass data to procedures and the code in the procedure can work on that data. As mentioned above, there are two types of procedures in Visual Basic .NET: Sub procedures and functions. Sub procedures do not return a value, while functions do.
Module Module1 Sub Main() System.Console.WriteLine("Hello from Visual Basic") End Sub End Module
Module Module1 Sub Main() DisplayMessage("Hello from Visual Basic") End Sub End Module Module Module1 Sub Main() Dim intValue As Integer = 2 System.Console.WriteLine("{0}+{1}={2}", _ intValue, intValue, Addem(intValue, intValue)) End Sub End Module Sub DisplayMessage(ByVal strText As String) System.Console.WriteLine(strText) End Sub

Function Addem(ByVal int1 As Integer, ByVal int2 As Integer) As Long Return int1 + int2 End Function

Understanding Scope
The scope of an element in your code is all the code that can refer to it without qualifying its name (or making it available through an Imports statement). an element's scope is its accessibility in your code. As we write larger programs, scope will become more important, because we'll be dividing code into classes, modules, procedures, and so on. You can make the elements in those programming constructs private, which means they are tightly restricted in scope. an element can have scope at one of the following levels: Block scopeavailable only within the code block in which it is declared Procedure scopeavailable only within the procedure in which it is declared Module scopeavailable to all code within the module, class, or structure in which it is declared Namespace scopeavailable to all code in the namespace

Declaring a variable in a procedure gives it procedure scope, and so on. Inside these levels of scope, you can also specify the scope of an element when you declare it. Here are the possibilities in VB .NET: Public The Public statement declares elements to be accessible from anywhere within the same project, from other projects that reference the project, and from an assembly built from the project. You can use Public only at module, namespace, or file level. This means you can declare a Public element in a source file or inside a module, class, or structure, but not within a procedure. Protected The Protected statement declares elements to be accessible only from within the same class, or from a class derived from this class. You can use Protected only at class level, and only when declaring a member of a class. Friend The Friend statement declares elements to be accessible from within the same project, but not from outside the project. You can use Friend only at module, namespace, or file level. This means you can declare a Friend element in a source file or inside a module, class, or structure, but not within a procedure. Protected Friend The Protected statement with the Friend keyword declares elements to be accessible either from derived classes or from within the same project, or both. You can use Protected Friend only at class level, and only when declaring a member of a class. Private The Private statement declares elements to be accessible only from within the same module, class, or structure. You can use Private only at module, namespace, or file level. This means you can declare a Private element in a source file or inside a module, class, or structure, but not within a procedure.

Module Module1 Sub Main() Dim intValue As Integer = 1 If intValue = 1 Then Dim strText As String = "No worries." System.Console.WriteLine(strText) End If System.Console.WriteLine(strText) 'Will not work! End Sub End Module Module Module1 Sub Main() System.Console.WriteLine(Module2.Function1()) 'Will not work! End Sub End Module Module Module2 Private Function Function1() As String Return "Hello from Visual Basic" End Function End Module

Module Module1 Sub Main() System.Console.WriteLine(Module2.strData) End Sub End Module Module Module2 Public strData As String = "Hello from Visual Basic" End Module

In fact, when you declare elements like strData public throughout the program, need not qualify their names in other code, so it can refer to strData in Module1 as well: Module Module1 Sub Main() System.Console.WriteLine(strData) End Sub End Module Module Module2 Public strData As String = "Hello from Visual Basic" End Module

Creating Sub Procedures


[ <attrlist> ] [{ Overloads | Overrides | Overridable | NotOverridable | MustOverride | Shadows | Shared }] [{ Public | Protected | Friend | Protected Friend | Private }] Sub name [(arglist)] [ statements ] [ Exit Sub ] [ statements ] End Sub Module Module1 Sub Main() DisplayMessage("Hello from Visual Basic") End Sub Sub DisplayMessage(ByVal strText As String) System.Console.WriteLine(strText) End Sub End Module

Creating Functions
[ <attrlist> ] [{ Overloads | Overrides | Overridable | NotOverridable | MustOverride | Shadows | Shared }] [{ Public | Protected | Friend | Protected Friend | Private }] Function name[(arglist)] [ As type ] [ statements ] [ Exit Function ] [ statements ] End Function
Module Module1 Sub Main() Dim intValue As Integer = 2 System.Console.WriteLine("{0}+{1}={2}", _ intValue, intValue, Addem(intValue, intValue)) End Sub Function Addem(ByVal int1 As Integer, ByVal int2 As Integer) As Long Return int1 + int2 End Function End Module

Commenting Your Procedures

Passing a Variable Number of Arguments

Specifying Optional Procedure Arguments


You also can make arguments optional in VB .NET procedures if you use the Optional keyword when declaring those arguments. Note that if you make one argument optional, all the following arguments must also be optional, and you have to specify a default value for each optional argument

Module Module1 Sub Main() DisplayMessage() End Sub Sub DisplayMessage(Optional ByVal strText As String = _ "Hello from Visual Basic") System.Console.WriteLine(strText) End Sub End Module

Preserving a Variable's Values between Procedure Calls

Creating Procedure Delegates


Sometimes, it's useful to be able to pass the location of a procedure to other procedures. That location is the address of the procedure in memory, and it's used in VB .NET to create the callback procedures

Creating Properties
[ <attrlist> ] [ Default ] [ Public | Private | Protected | Friend | Protected Friend ] [ ReadOnly | WriteOnly ] [Overloads | Overrides ] [Overridable | NotOverridable] | MustOverride | Shadows | Shared] Property varname([ parameter list ]) [ As typename ] [ Implements interfacemember ] [ <attrlist> ] Get [ block ] End Get [ <attrlist> ] Set(ByVal Value As typename ) [ block ] End Set End Property

Handling Exceptions
Exceptions are just runtime errors; in Visual Basic (unlike some other languages), the terms exception handling and error handling have become inter-changeable. Exceptions occur when a program is running (as opposed to syntax errors, which will prevent VB .NET from running your program at all). You can trap such exceptions and recover from them, rather than letting them bring your program to an inglorious end. there are two ways of handling errors that occur at run time in VB .NETwith structured and unstructured exception handling. Unstructured Exception Handling Module Module1 Sub Main() On Error Goto Handler Exit Sub Handler: End Sub End Module

Module Module1 Sub Main() Dim int1 = 0, int2 = 1, int3 As Integer On Error Goto Handler int3 = int2 / int1 System.Console.WriteLine("The answer is {0}", int3) Handler: System.Console.WriteLine("Divide by zero error") Resume Next End Sub End Module
When you run this code, you see this message: Divide by zero error

handle exception objects such as OverflowException like this:

Using Resume Next and Resume Line


One of the most useful aspects of unstructured exception handling is the Resume statement, which lets you resume program execution even after an exception has occurred. Resume to resume execution with the statement that caused the exception. Resume Next to resume execution with the statement after the one that caused the exception. Resume line, where line is a line number or label that specifies where to resume execution

Using On Error GoTo 0


To turn off unstructured exception handling, you can use the On Error GoTo 0 or On Error GoTo -1 statements

Getting an Exception's Number and Description

Raising an Exception Intentionally


There are cases in programs where you might want to create an exception because, although no Visual Basic trappable exception has occurred, some situation may have occurred that's incompatible with your program's logic. You can create an exception intentionally, called raising an exception, with the Visual Basic Err object's Raise method
Raise(ByVal Number As Integer, Optional ByVal Source As Object = Nothing, Optional ByVal Description As Object = Nothing, Optional ByVal HelpFile As Object = Nothing, Optional ByVal HelpContext As Object = Nothing)

Here are the arguments for the Raise method: NumberLong integer that identifies the nature of the exception. SourceString expression naming the object or application that generated the exception; use the form project.class. (If source is not specified, the name of the current Visual Basic project is used.) DescriptionString expression describing the exception. HelpfileThe path to the Help file in which help on this exception can be found. HelpcontextA context ID identifying a topic within helpfile that provides help for the exception.

Structured Exception Handling


Visual Basic uses an enhanced version of the TryCatchFinally syntax already supported by other languages

Module Module1 Sub Main() Dim int1 = 0, int2 = 1, int3 As Integer Try int3 = int2 / int1 System.Console.WriteLine("The answer is {0}", int3) Catch e As Exception System.Console.WriteLine(e.ToString) End Try End Sub End Module

Exception Filtering in the Catch Block


When you're handling exceptions, you usually want to handle different types of exceptions differently, according to the nature of the exception that occurred. This process is called filtering. There are actually two ways to filter exceptions with Catch blocks. First, you can filter on specific classes of exceptions, which means you have to prepare for the various exceptions you want to handle. The second exception-filtering option lets you use the Catch statement to filter on any conditional expression, using the When keyword.

Exceptions are based on the Visual Basic Exception class Exception class, which lists the classes derived from it:

Each derived class itself has many derived classes, and if you keep searching (each class above is a hyperlink in the documentation, so you just keep clicking), you'll eventually find the OverflowException class, which is based on the ArithmeticException class, which is based on the SystemException class, which is based on the Exception class:

The first exception-filtering option

The second exception-filtering option

Using Multiple Catch Statements

Using Finally
The code in the Finally block, if there is one, is always executed in a TryCatchFinally statement, even if there was no exception, and even if you execute an Exit Try statement. This allows you to deallocate resources and so on

Throwing an Exception
You can throw an exception using the Throw statement, and you can also rethrow a caught exception using the Throw statement.

Throwing a Custom Exception


You can customize the exceptions you throw by creating a new exception object based on the ApplicationException object.

Summary
Sub Procedures and Functions Understanding Scope Creating Sub Procedures Creating Functions Preserving a Variable's Values between Procedure Calls Creating Procedure Delegates Creating Properties Handling Exceptions Throwing a Custom Exception

You might also like