You are on page 1of 13

Procedures:

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
 Sub procedures or Subs
Functions return a value, whereas Subs do not return a value.

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.
 FunctionName − indicates the name of the function
 ParameterList − specifies the list of the parameters
 ReturnType − specifies the data type of the variable the function returns

VB.NET Dialog Box

 A Dialog box is a temporary Window for an application that accepts user response
through mouse or keyboard to open a file, save a file, notifications, alert messages,
color, print, openfile dialog box, etc.
 It is also useful to create communication and interaction between the user and the
application. Furthermore, the dialog box appears in a form when the program needs to
interact with users, such as when an error occurs, an alert message, acknowledgment
from the user or when the program requires immediate action or whether the decision
is to be saved based on the changes.

All VB.NET Dialog box inherits the CommonDialog class and overrides


the RunDialog() method of the base class to create the OpenFileDialog box, PrintDialogbox,
Color, and Font Dialog box. The RunDialog() method is automatically called in
a Windows form when the dialog box calls its ShowDialog() method.

There are following functions of the ShowDialog() method that can be called at run time in
the Windows Form.

o Abort: The Abort Dialog box is used when a user clicks on the Abort button to return
the DialogResult.Abort value.
o Ignore: The Ignore Dialog box is used when a user clicks on the Ignore button to
return the DialogResult.Ignore.
o None: It is used to return nothing when the user clicks on the None button, and the
dialog box is continued running.
o OK: When the user clicks the OK button of the Dialog box, it returns a
DialogResult.OK,
o Cancel: When a user clicks on the Cancel button of the Dialog Box, it returns
DialogResult.Cancel,
o Yes: When a user clicks the Yes button of the dialog box, it returns DialogResult.Yes.
o Retry: When a user clicks on the Dialog Box Retry button, it returns a
DialogResult.Retry,
o No: When a user clicks on the No button of the Dialog box, it returns
DialogResult.No,

There are the commonly used dialog box controls in the VB.NET Windows Form.ec

1. Color Dialog Box: It is used to display the color dialog box that allows the user to
select a color from the predefined colors or specify the custom colors.
2. Font DialogBox: It is used to create a Font dialog box that allows the user to select
the font, font size, color, and style to be applied to the current text selection.
3. OpenFile Dialog Box: It is used to create a prompt box that allows the users to select
a file to open and allows the selection of multiple files.
4. Print Dialog Box: It is used to create a print dialog box that allows the user to print
documents by selecting the printer and setting of the page printed through the
Windows application.
5. A file is a collection of data stored in a disk with a specific name and a
directory path. When a file is opened for reading or writing, it becomes
a stream.
6. The stream is basically the sequence of bytes passing through the
communication path. There are two main streams: the input stream and
the output stream. The input stream is used for reading data from file (read
operation) and the output stream is used for writing into the file (write
operation).

VB.Net I/O Classes


 The System.IO namespace has various classes that are used for
performing various operations with files, like creating and deleting files,
reading from or writing to a file, closing a file, etc.
The following table shows some commonly used non-abstract classes in the
System.IO namespace −

I/O Class Description

BinaryReader Reads primitive data from a binary stream.

BinaryWriter Writes primitive data in binary format.

BufferedStream A temporary storage for a stream of bytes.

Directory Helps in manipulating a directory structure.

DirectoryInfo Used for performing operations on directories.

DriveInfo Provides information for the drives.

File Helps in manipulating files.

FileInfo Used for performing operations on files.

FileStream Used to read from and write to any location in a file.

MemoryStream Used for random access of streamed data stored in memory.

Path Performs operations on path information.

StreamReader Used for reading characters from a byte stream.

StreamWriter Is used for writing characters to a stream.

StringReader Is used for reading from a string buffer.

StringWriter Is used for writing into a string buffer.


The FileStream Class
The FileStream class in the System.IO namespace helps in reading from,
writing to and closing files. This class derives from the abstract class Stream.

Parameter Description

FileMode The FileMode enumerator defines various methods for opening files. The


members of the FileMode enumerator are −
 Append − It opens an existing file and puts cursor at the end of file,
or creates the file, if the file does not exist.
 Create − It creates a new file.
 CreateNew − It specifies to the operating system that it should
create a new file.
 Open − It opens an existing file.
 OpenOrCreate − It specifies to the operating system that it should
open a file if it exists, otherwise it should create a new file.
 Truncate − It opens an existing file and truncates its size to zero
bytes.

FileAccess FileAccess enumerators have members: Read, ReadWrite and Write.

FileShare FileShare enumerators have the following members −


 Inheritable − It allows a file handle to pass inheritance to the child
processes
 None − It declines sharing of the current file
 Read − It allows opening the file for reading
 ReadWrite − It allows opening the file for reading and writing
 Write − It allows opening the fil

The File System Object (FSO)

 object model provides an object-based tool for working with folders and files. Using
"object.method" syntax, it exposes a comprehensive set of properties and methods to
perform file system operations such as creating, moving, deleting, and providing
information about folders and files. The FSO also provides methods for reading and
writing sequential text files, however it does NOT have methods for processing binary
or random files.

Exception Handling

An exception refers to an event that is triggered during the execution of a

program that goes against the flow, disrupting the program. An exception in

VB.NET is meant to represent a error that occurs due to compiler being

unable to handle an unexpected situation. As a result, the program flow is

stopped and terminated.catch, finally and throws.

 Try: A Try Block is a block of code which generates different

exceptions within the application. To handle these exceptions thrown

in the try block we use catch block. Thus the try block is always

followed by one or more catch blocks.

 Catch: A Catch Block is a block of code that contains the statements

which handle the exceptions by using an exception handler on the

statement where the issue occurred. The catch block is mainly the

handling of exception by different Exception Classes defined in the

library of Exceptions.

 Finally: A Finally Block is a block of code that contains statements

that are mandatory statements to be executed irrespective of


whether the exception is thrown or not thrown. Suppose I have to

open a file, read the file, write the file and close the file. In the try

block, statements are like open a file, read a file and write a file that

may or may not throw an exception but the file needs to be closed

before the program ends. Thus the final block has always statements

like closing the files, closing the database connection, the closing of

program, etc.

 Throw: When an issue occurs this statement throws an exception.

This exception may be build in or user-defined exception.

Syntax:

The code for Try-Catch Block is as per the following

Try

Catch <Exception Name> As <Exception Type>

[Catch1 Statements] Catch <Exception Name> As

<Exception Type>

[Catch2 Statements] Catch <Exception Name> As

<Exception Type>
[Catch3 Statements] Finally

[Finally Statements] End Try

Here, there is more than one catch block displayed in the above syntax to

catch a different type of exceptions raised by the try block. It may happen

that more than one exception being thrown by the try block and only one

catch block is available, then to catch all the exceptions we will need one or

multiple catch statements. And thus we have written more than one catch

statement in the syntax above.

Exception Classes in VB.NET


There are two Exceptions mainly

1. System.SystemException

2. System.ApplicationException

System.SystemException is a class for all built-in system exceptions or we

can say that when running time error when occurred the system exception

classes like DivideByZeroException, IndexOutOfRangeException,

StackOverflowException is instantiated.
System.ApplicationException is a class that executes the exceptions defined

by the programmer or developer withing the application. It throws a user-

defined exception which is derived from this System.ApplicationException

class.

 System.IndexOutOfRangeException: This exception handles the

errors caused by an array index which is out of range.s Suppose we

have an array of 5 array lengths and we loop this 6 times the 6th time

the program will through IndexOutOfRangeException.

 System.DivideByZeroException: This exception handles the errors

caused when a number is divided by zero which is against the

universal rule that a number being divided by zero will result in an

abnormal termination of the program.

 System.FormatException: This exception handles the errors caused

when the user inputs a character or a string when asked for a number

or integer. say the user needs to enter 5 but inputs say ‘y’ then this

exception will occur.

NAMESPACESNamespaces organize the objects defined in an assembly.


Assemblies can contain multiple namespaces, which can in turn contain other
namespaces. Namespaces prevent ambiguity and simplify references when using

large groups of objects such as class libraries.

For example, the .NET Framework defines the ListBox class in


the System.Windows.Forms namespace. The following code fragment shows how to
declare a variable using the fully qualified name for this class:

VBCopy

Dim LBox As System.Windows.Forms.ListBox


Avoiding Name Collisions

.NET Framework namespaces address a problem sometimes called namespace


pollution, in which the developer of a class library is hampered by the use of similar
names in another library. These conflicts with existing components are sometimes
called name collisions.

For example, if you create a new class named ListBox, you can use it inside your
project without qualification. However, if you want to use the .NET
Framework ListBox class in the same project, you must use a fully qualified reference
to make the reference unique. If the reference is not unique, Visual Basic produces an
error stating that the name is ambiguous. The following code example demonstrates
how to declare these objects:

VBCopy

' Define a new object based on your ListBox class.


Dim LBC As New ListBox
' Define a new Windows.Forms ListBox control.
Dim MyLB As New System.Windows.Forms.ListBox

The following illustration shows two namespace hierarchies, both containing an


object named ListBox:

By default, every executable file you create with Visual Basic contains a namespace
with the same name as your project. For example, if you define an object within a
project named ListBoxProject, the executable file ListBoxProject.exe contains a
namespace called ListBoxProject.
Multiple assemblies can use the same namespace. Visual Basic treats them as a single
set of names. For example, you can define classes for a namespace
called SomeNameSpace in an assembly named Assemb1, and define additional classes for
the same namespace from an assembly named Assemb2.

When you define a class, you define a blueprint for a data type. This doesn't
actually define any data, but it does define what the class name means, that is,
what an object of the class will consist of and what operations can be performed on
such an object.
Objects are instances of a class. The methods and variables that constitute a class
are called members of the class.

Class and objects


A class definition starts with the keyword Class followed by the class name; and the
class body, ended by the End Class statement. Following is the general form of a
class definition −
[ <attributelist> ] [ accessmodifier ] [ Shadows ] [ MustInherit
| NotInheritable ] [ Partial ] _
Class name [ ( Of typelist ) ]
[ Inherits classname ]
[ Implements interfacenames ]
[ statements ]
End Class

Where,
 attributelist is a list of attributes that apply to the class. Optional.
 accessmodifier defines the access levels of the class, it has values as -
Public, Protected, Friend, Protected Friend and Private. Optional.
 Shadows indicate that the variable re-declares and hides an identically
named element, or set of overloaded elements, in a base class. Optional.
 MustInherit specifies that the class can be used only as a base class and
that you cannot create an object directly from it, i.e., an abstract class.
Optional.
 NotInheritable specifies that the class cannot be used as a base class.
 Partial indicates a partial definition of the class.
 Inherits specifies the base class it is inheriting from.
 Implements specifies the interfaces the class is inheriting from.

Member Functions and Encapsulation


A member function of a class is a function that has its definition or its prototype
within the class definition like any other variable. It operates on any object of the
class of which it is a member and has access to all the members of a class for that
object.
Member variables are attributes of an object (from design perspective) and they are
kept private to implement encapsulation. These variables can only be accessed
using the public member functions.
Constructors and Destructors
A class constructor is a special member Sub of a class that is executed whenever
we create new objects of that class. A constructor has the name New and it does
not have any return type.
A default constructor does not have any parameter, but if you need, a constructor
can have parameters. Such constructors are called parameterized constructors. 
A destructor is a special member Sub of a class that is executed whenever an
object of its class goes out of scope.
A destructor has the name Finalize and it can neither return a value nor can it take
any parameters. Destructor can be very useful for releasing resources before
coming out of the program like closing files, releasing memories, etc.
Destructors cannot be inherited or overloaded.

Inheritance
One of the most important concepts in object-oriented programming is that of
inheritance. Inheritance allows us to define a class in terms of another class which
makes it easier to create and maintain an application. This also provides an
opportunity to reuse the code functionality and fast implementation time.
When creating a class, instead of writing completely new data members and
member functions, the programmer can designate that the new class should inherit
the members of an existing class. This existing class is called the base class, and
the new class is referred to as the derived class.

Base & Derived Classes


A class can be derived from more than one class or interface, which means that it
can inherit data and functions from multiple base classes or interfaces.
The syntax used in VB.Net for creating derived classes is as follows −
<access-specifier> Class <base_class>
...
End Class
Class <derived_class>: Inherits <base_class>
...
End Class

Multithreading
When two or more processes execute simultaneously in a program, the process is
known as multithreading. And the execution of each process is known as the thread.
A single thread is used to execute a single logic or task in an application. By default,
each application has one or more threads to execute each process, and that thread is
known as the main thread.
To create and access a new thread in the Thread class, we need to import
the System.Threading namespace. When the execution of a program begins in
VB.NET, the Main thread is automatically called to handle the program logic. And if
we create another thread to execute the process in Thread class, the new thread will
become the child thread for the main thread.

Create a new Thread


In VB.NET, we can create a thread by extending the Thread class and pass the
ThreadStart delegate as an argument to the Thread constructor. A ThreadStart() is a
method executed by the new thread. We need to call the Start() method to start the
execution of the new thread because it is initially in the unstart state. And the
PrintInfo parameter contains an executable statement that is executed when
creating a new thread.

1. ' Create a new thread  
2. Dim th As Thread = New Thread( New ThreadStart(PrintInfo)  
3. ' Start the execution of newly thread  

Thread Methods
The following are the most commonly used methods of Thread class.

Method Description

Abort() As the name defines, it is used to terminate the execution of a thread.

AllocateDataSlot() It is used to create a slot for unnamed data on all threads.

AllocateNamedDatsSlot() It is used to create a slot for defined data on all threads.

Equals() It is used to check whether the current and defined thread object are equal.

Interrupt() It is used to interrupt a thread from the Wait, sleep, and join thread state.

Join() It is a synchronization method that stops the calling thread until the execu
thread completes.

Resume() As the name suggests, a Resume() method is used to resume a thread that
been suspended.

Sleep() It is used to suspend the currently executing thread for a specified time.

Start() It is used to start the execution of thread or change the state of an ong
instance.

Suspend() It is used to stop the currently executing thread.

Thread Life Cycle


In VB.NET Multithreading, each thread has a life cycle that starts when a new object is
created using the Thread Class. Once the task defined by the thread class is
complete, the life cycle of a thread will get the end.

State Description

Unstarted When we create a new thread, it is initially in an unstarted state.

Runnable When we call a Start() method to prepare a thread for running, the runnable
situation occurs.

Running A Running state represents that the current thread is running.

Not It indicates that the thread is not in a runnable state, which means that the
Runnable thread in sleep() or wait() or suspend() or is blocked by the I/O operation.

Dead If the thread is in a dead state, either the thread has been completed its work
or aborted.

You might also like