0% found this document useful (0 votes)
19 views36 pages

Visual Basic .NET Programming Basics

This document discusses various aspects of visual programming in Visual Basic .NET, including: - Types of controls like text boxes, buttons, checkboxes etc. that can be used in Windows forms - The differences between sub procedures and functions - How to define the scope of variables and elements at different levels like block, procedure, module etc. - How to create, comment and pass arguments to sub procedures and functions - How exceptions are handled through both structured and unstructured exception handling techniques

Uploaded by

xerses_pasha
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views36 pages

Visual Basic .NET Programming Basics

This document discusses various aspects of visual programming in Visual Basic .NET, including: - Types of controls like text boxes, buttons, checkboxes etc. that can be used in Windows forms - The differences between sub procedures and functions - How to define the scope of variables and elements at different levels like block, procedure, module etc. - How to create, comment and pass arguments to sub procedures and functions - How exceptions are handled through both structured and unstructured exception handling techniques

Uploaded by

xerses_pasha
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd

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() [Link]("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 [Link]("{0}+{1}={2}", _ intValue, intValue, Addem(intValue, intValue)) End Sub End Module Sub DisplayMessage(ByVal strText As String) [Link](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." [Link](strText) End If [Link](strText) 'Will not work! End Sub End Module Module Module1 Sub Main() [Link](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() [Link]([Link]) 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() [Link](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) [Link](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 [Link]("{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") [Link](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 [Link]("The answer is {0}", int3) Handler: [Link]("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 [Link]. (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 [Link]("The answer is {0}", int3) Catch e As Exception [Link]([Link]) 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

Common questions

Powered by AI

Visual Basic .NET offers structured and unstructured exception handling strategies. Structured handling uses Try...Catch...Finally blocks to catch and manage specific exceptions robustly, allowing for detailed control flows and cleanup with Finally blocks. Unstructured handling with On Error GoTo permits simpler error management using labels and 'Resume' statements for quick recovery. Combined, these strategies allow for detailed, specific error management as well as broad, simple error recovery, complementing each other's strengths in different programming scenarios .

The 'Friend' access level allows elements to be accessible within the same project but not outside it, suitable for internal project components like utilities or helpers that should not be exposed publicly. The 'Protected' level limits accessibility to the class itself and any derived classes, useful for inheritance scenarios where internal logic or state should be preserved but not exposed externally. 'Friend' facilitates project-wide accessibility, while 'Protected' supports inheritance and encapsulation .

In unstructured exception handling, the 'Resume' statement variants influence program control flow after an exception. 'Resume' resumes execution at the statement that caused the exception, allowing the operation to retry. 'Resume Next' skips to the statement following the one that failed, bypassing the error. 'Resume Line' allows resumption at a specified label or line number, providing custom recovery paths. These variants enable flexible error recovery but can complicate code maintenance if overused .

The 'Public' access modifier makes an element accessible from anywhere within the same project, other referencing projects, and any assembly built from the project. In contrast, the 'Private' modifier restricts access to within the same module, class, or structure only. This distinction allows developers to expose necessary interfaces and keep other details hidden, maintaining encapsulation and preventing unintended interactions .

Exception handling in Visual Basic .NET can be implemented using structured and unstructured approaches. Structured exception handling uses Try...Catch...Finally blocks, which are more robust and allow for specific exception types to be caught and handled. The Catch block can filter specific exceptions or conditional expressions using the 'When' keyword. Unstructured handling uses the On Error GoTo statement to manage errors through labels and 'Resume' statements. Although more straightforward, it is less precise than structured handling .

Sub procedures in Visual Basic .NET do not return a value, while functions do. This distinction impacts program design by determining whether a procedure can be used to calculate and return a value within a program. Subs are typically used for executing a sequence of statements, whereas functions are suitable when a calculation or value result is needed. This separation encourages developers to design code that separates the flow of control (using Subs) from data calculations or manipulations (using Functions).

Optional parameters in Visual Basic .NET procedures are declared using the 'Optional' keyword and must follow all required parameters. They can enhance flexibility by allowing procedures to be called with varying numbers of arguments, defaulting to predefined values if not supplied. This feature simplifies function overloading and makes API interfaces more intuitive by reducing the need for multiple methods with varying parameters .

Multiple Catch statements in structured exception handling allow different types of exceptions to be handled separately within a single Try block. Each Catch can specify a distinct exception class, enabling tailored handling and recovery strategies for various error types. This approach increases robustness by ensuring that each exception type gets appropriate attention and allows for specific exception-related actions, such as logging or resource cleanup, enhancing code clarity and maintainability .

In Visual Basic .NET, scope determines the accessibility of elements in the code based on where they are declared. Scope levels include block, procedure, module, and namespace scope. It's crucial in managing larger programs because it enables developers to control where and how elements can be accessed, ensuring that variables or functions are only available where needed. Proper scope management prevents unintended interactions and makes code modular and easier to debug or extend .

Properties in Visual Basic .NET enhance code readability and encapsulation by allowing controlled access to class variables. They use Get and Set procedures to retrieve and validate data being assigned to class fields, enabling developers to hide implementation details while providing intuitive access points. This approach allows for data validation or conversion internally, ensuring that external code interacts with class state safely and predictably, improving both security and code maintainability .

You might also like