0% found this document useful (0 votes)
2K views

PGDCA-II Programming in VB - Net Compiled by Prafulla Sir

The document contains the syllabus for a course on "Programming in VB.NET". The syllabus covers 5 units: 1. Introduction to the .NET framework - Includes components of .NET, CLR, MSIL, assemblies, namespaces, garbage collection. 2. Programming with the .NET framework - Covers Windows forms, Visual Studio IDE, controls, data types, variables, operators, methods, events. 3. Control structures - Includes conditional statements, loops, arrays, methods, exception handling. 4. GUI programming - Covers GUI development with Windows forms, menus, dialog boxes. 5. Database programming with ADO.NET - Includes ADO.NET architecture, datasets

Uploaded by

Vijayant Verma
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2K views

PGDCA-II Programming in VB - Net Compiled by Prafulla Sir

The document contains the syllabus for a course on "Programming in VB.NET". The syllabus covers 5 units: 1. Introduction to the .NET framework - Includes components of .NET, CLR, MSIL, assemblies, namespaces, garbage collection. 2. Programming with the .NET framework - Covers Windows forms, Visual Studio IDE, controls, data types, variables, operators, methods, events. 3. Control structures - Includes conditional statements, loops, arrays, methods, exception handling. 4. GUI programming - Covers GUI development with Windows forms, menus, dialog boxes. 5. Database programming with ADO.NET - Includes ADO.NET architecture, datasets

Uploaded by

Vijayant Verma
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 91

SYLLABUS

PGDCA- 106 Navbodh


PROGRAMMING IN VB.NET
Unit- I: Introduction to .Net framework

Overview of .Net framework features & architecture, Managed Execution process,


CLR, common language specification, JIT Compilation, MSIL, Namespaces, Assemblies,
metadata, Common Type System, Visual development & event driven programming, cross
language, interoperability, Garbage collection.

Unit II: Programming with .Net Framework

Windows form, working with Visual Studio IDE, creating a .NET solution, MDI
application, components and controls, Data types, variables, Type conversions, operators,
Methods and events, Scope and life time of variables, Creating Enumertions.

Unit III: Control Structures

Control structures, conditional statements, loops, arrays, types of methods, method


data, creating Sub Procedures and Functions, Msgbox, Inputbox, Introduction to exception
handling- try catch statement, finally statement, throw, user define Exception.

Unit IV: GUI Programming

GUI Programming with window forms, Showing & hiding forms, Textbox, RichText
box, Label, Button, Listox, Comboboxes, Checkbox, Picturebox, Radio button, Toggle
Button, Panel, Groupbox, Scrollbar, Timer, Dialog boxes, OpenFile Dialog, SaveFile dialog,
Print dialog, Font dialog, Color dialog, Designing menus and sub menus.

Unit V: Database programming with ADO.net

ADO .NET Architecture, NET data provider, dataset components, creating database
applications using Windows forms (Database connectivity through ADO .NET), Accessing
data using server explorer, Data Adapters & Data sets, Command & Data reader, data bind
control, displaying data in data grid.

Books Recommended

 MSDN online- by Microsoft

 Visual Basic .NET Complete-by BPB Publications, New Delhi


 The Complete Reference VB .NET 2003- by Bill Evjen & others, Willey Dremtech
India (P) Ltd. New Delhi
Table of Contents
SYLLABUS...............................................................................................................................................2
UNIT I Introduction to .NET Framework................................................................................................5
Q 1. What is .Net Framework?...........................................................................................................5
Q 2. Describe the architecture of .Net Framework............................................................................5
Q 3. Write down the various main components of .NET Framework................................................5
Q 4. What is a common type system (CTS)?......................................................................................7
Q 5. What is Common Language Specification?.................................................................................8
Q 6. What is MSIL (Microsoft Intermediate Language)?....................................................................8
Q 7. What is Assembly in VB.Net?.....................................................................................................9
Q 8. What is Class Library in VB.Net?.................................................................................................9
Q 9. Write the execution process of .NET........................................................................................10
Q 10. Differentiate between Namespace and Assembly. Or What do you understand by
Namespace and Assembly?.............................................................................................................11
Q 11. How to force Garbage Collection?.........................................................................................12
Unit II Programming with .NET Framework.........................................................................................14
Q 1. Discuss about Windows Form in VB.NET..................................................................................14
Q 2. Discuss about the introduction of Visual Studio.......................................................................15
Q 3. How to Create Project in VB.Net? or Write down the steps to create a VB.Net solution.........16
Q 4. Explain the IDE (Integrated Development Environment) of VB.NET.........................................18
Q 5. Describe the Components of Visual Studio..............................................................................18
Q 6. Differentiate between static and constant. Or What are a variable and constant?.................23
Q 7. How to declare variable in VB.Net?..........................................................................................23
Q 8. What are Data types in VB.Net?...............................................................................................26
Q 9. What do you understand by Variables?...................................................................................28
Q 10. Define various type conversions in Visual Basic.....................................................................30
Q 11. What is an operator?.............................................................................................................31
Q 12. What do you understand by Events? Define various kinds of VB.Net Events.........................34
Q 13. Describe Variable’s Scope and Lifetime of a Variable.............................................................39
Q 14. How to create enumeration in VB.Net?.................................................................................40
Unit III Control Structure.....................................................................................................................43
Q 1. What do you understand by Control structure in VB.Net?.......................................................43
Q 2. What do you understand by Array?.........................................................................................47
Q 3. What is method in VB.Net?......................................................................................................48
Q 4. What are the types of method?...............................................................................................49
Q 5. How can method get the data?................................................................................................50
Q 6. Differentiate between functions and sub procedure...............................................................51
Q 7. How can Message box be used in VB.Net? Give suitable example...........................................57
Q 8. Define InputBox function in VB.Net.........................................................................................58
Q 9. What is an Exception?..............................................................................................................59
Q 10. Write down the various exception classes in .Net framework...............................................60
Q 11. How can exception handling problem be solved in VB.Net?..................................................61
Q 12. How to create User defined exceptions in VB.Net?...............................................................61
Unit IV GUI Programming...................................................................................................................64
Q 1. What do you understand by OOPs? Or Write down the various features of OOPS..................64
Q 2. What do you understand by an Inheritance in VB.Net?...........................................................65
Q 3. What are Access Specifiers in VB.NET?....................................................................................66
Q 4. What is Overloading in VB.Net.................................................................................................66
Q 5. Where can MyBase keyword be used?....................................................................................68
Q 6. How to use MyClass Keyword in VB.Net?................................................................................69
Q 7. Discuss the overview of OLE (Object Linking and Embedding) in VB.Net.................................70
Q 8. What is windows form? How can we work with Form?...........................................................71
Unit V Database Programming with ADO.net.....................................................................................75
Q 1. Describe the ADO.NET Architecture.........................................................................................75
Q 2. Describe the ADO.Net Object Model.......................................................................................77
Q 3. How to access Data Using Server Explorer?.............................................................................84
Q 4. Discuss about SQLDB in VB.Net................................................................................................85
Q 5. How to display Data on data bound controls...........................................................................87
Q 6. How to Display data on data grid?...........................................................................................88
UNIT I
Introduction to .NET Framework

Q 1. What is .Net Framework?


Ans.The dot net framework is a software framework, developed in 2002 by a Microsoft
company. The dot net framework provides a common platform to run (execute) applications
created in different programming languages. That is, it is a framework with which Windows
applications and Web applications can be easily created and run.
Dot Net Framework Features (Characteristics of .net framework)
1. Common Language Runtime 7. Application domains
(CLR) 8. Security
2. Manage Execution 9. Facility to configure and deploy
3. Common type system dot net applications
4. Dot Net Framework Library 10. Web services
5. Namespace 11. Windows form
6. Assemblies 12. ASP.NET

Q 2. Describe the architecture of .Net Framework.

Ans.The .NET Framework is a software development framework developed by Microsoft in


2002. The .NET Framework runs only in the Windows operating system .NET is a framework
in which web-based and windows-based software (Application) is developed within the
Microsoft environment. CLR (common language
runtime) in .NET Framework) Acts like the soul of
the framework. The .NET Framework has a very
large class library called the framework class
library (FCL).
The .NET Framework is object-oriented just like
the Java (java) language but it is not platform
independent i.e. it runs only on the windows
platform.The .NET framework is a framework that
supports many languages. The framework
provides a GUI (graphical user interface).

Note: - The thing to note here is that .NET is not a language but it is a software and
language neutral platform.

Q 3. Write down the various main components of .NET Framework

Ans.Following are the main components of .NET Framework

 CLR(common language runtime)  NET framework class library(FCL)

 CTS(common type system)  NET languages.


CLR(Common language runtime)
It acts like a virtual machine and executes all languages.
The CLR transforms the source code into byte code which we call CIL (common
intermediate language) or MSIL (Microsoft intermediate language) and Then at run-time,
CLR converts this CIL code or MSIL code into native code by the JIT compiler.
CTS(Common type system)
CTS describes a group of types that are used equally in all .NET languages.
For example: - A class library is used in C # and this class library is also used in VB.NET as
this class library is defined by CTS.
It can be types, value types and reference types. Value types are passed by values that are
stored in the stack. Reference types are passed by references that are stored in the heap.

.NET framework class library(FCL)

FCL is a standard library of Microsoft and is a library of reusable classes, interfaces and
value types.It is used to develop web-based, Windows GUI applications and ASP.NET
applications.

.NET languages

The .NET Framework supports visual basic, C, C ++, C #, asp.net, Jscript.net, ADO.NET
and other .NET languages.

CLR (Common language Run time)

The second part of the Net Framework is the Common Language Runtime (CLR).CLR is
considered as the first layer of the dot net framework CLR defines the execution
environment of programs written in dot net ie CLR provides the user an environment under
which the user can easily create any application in the shortest time (Develop) can be
executed.
When you write applications for the .Net framework in these languages, such as VB.Net or C
#, your source-code is never directly compiled into machine code.
Instead, the C # compiler in VB converts your code into a special language called MSIL
(Microsoft Intermediate Language).
MSIL is largely an object-oriented assembly language. But like an assembly language, it
does not depend on every CPU. It is a low-level and platform-independent language.
When your application is executed, the MSIL code is compiled into "just-in-time" machine
code.JITTER (the just-in-time compiler) does this work.
Generally, your entire application is not compiled in machine code. Instead, only the called
method is compiled.
Actually .Net Framework understands only one language MSIL. But you can use VB.Net and
C # languagesto write applications, because compilers included in the .Net framework help
you compile code written in these languages into MSIL.
You can use the following languages for the .Net Framework -

 Ada  Perl  RPG

 COBOL  Pascal  Smalltalk

 Fortran  PHP

 JavaScript  Python

Most developers use VB.Net or C # to write ASP.Net applications.


CLR provides the following services along with the implementation of the program

 Compile the necessary code for the application.

 Allocating memory during program execution.

 Managing all threads included in the program.

 Handling the garbage collection

 Support exception handling.

CTS (Common Type System) is provided by CLR, which provides a secure environment for
running the program. CLR is also known as CLI (Common Language Infrastructure).
When the dot net program is compiled, the output of the program is not an execution file but
a file that contains a special type of code called Microsoft Intermediate Language MSIL.
The CLR converts this intermediate code into executable code when the program is
executed.
JIT Compiler converts MSIL into native code as required.
The CLR is mainly divided into five parts, which are as follows -

 Common Type System (CTS)  Common Intermediate Language


(CIL)
 Common Language Specification
(CLS)  Just In Time Compiler (JIT)

 Virtual execution system (VES)


Q 4. What is a common type system (CTS)?

Ans. Common type system (CTS)In the dot net framework, CTS (Common type system)
specifies the type systems
represented in computer memory
and their values
It helps to share information
between programs written in
different languages.
It supports Cross language
platform, due to which it helps in sharing information between programs written in different
language, it supports and fully implement an Object oriented model.
It is used to share objects of different languages on the same platform.
Example: - C # program can be used with the program of Visual Basic. It defines the rules
for sharing information between objects. It provides interaction between data types of
different languages. Thus CTS plays an important role in dot net.

Q 5. What is Common Language Specification?

Ans.

Q 6. What is MSIL (Microsoft Intermediate Language)?

Ans. MSIL (Microsoft


Intermediate Language)
MSIL is also known as
Common Intermediate
Language (CIL).
It is a low level human
readable Programming
Language. Which is available
in the Common Language
Infrastructure of the dot net.
This language is generated
when the language
supporting dot net is compiled. This language is run by the CLR. It is also called byte codes.
It is also called byte codes. This is object oriented assembly language which is executed by
CLR on the virtual machine.
When all the language used in dot net is compile, the language is converted to MSIL (CIL)
by specific compiler.
It does not change in direct machine code. CIL is a CPU and platform independent code.
After that, byte codes dot net CLR are converted to machine code and run the program.
MSIL codes can be executed on any environment that supports the dot net framework.
Executing MSIL
1. Source codes are converted to Common Intermediate language through a language
specific compiler.
2. Creates dot net assembly as per CIL.
3. This byte code goes to the CLR to be executed.
4. CLR converts them into machine code and executes them.

Q 7. What is Assembly in VB.Net?

Ans. AssembliesA logical group of one or more files in a dot net is called an assembly.
An Assemble is a collection of a single DLL (Dynamic Link Library) or EXE files.
In dot net assemblies, it is possible to retain many versions of a particular assembly.
Each assembly has a Manifest and Compile Code. Dot net assemblies are full Self
Describing. It is an important part of the dot net framework. It incorporates many types of
information to run the program, as well as it does the following.

 This includes the codes run by the CLR. Code of Microsoft Intermediate Language
cannot be executed without assembly. It forms an Associated Assembly.

 This defines the Security Limitations of the program. It processes the Request and
Permission to execute the program.

 This creates Type Limitations. All identified types are stored in the assembly.

 This defines Version Limitation.

 This creates the Deployment Unit.

 It supports the Side by Side Execution of the program.

An assembly can be either a DLL or an EXE.


The assembly file can be of two types.

 Single file assembly

 Multi File Assembly

Q 8. What is Class Library in VB.Net?

Ans. Class Library-The Microsoft Base Class Library is the most important part of the .Net
Framework. This is a library that can be used by all computer languages of dot net. It
provides common library for all. There are many common functions, methods and classes in
this library which are common for all dot net languages. These functions and methods are
used for various tasks.
Example: - File reading and writing, database interaction, XML documentation etc.
Following are some important .Net Library Classes and Namespaces.

 System: It is used to meet the basic requirements of Programming. It containers


Data Types and Conversion Functions. Example: String, Boolean, Date time Etc.

 System.Collection: It defines all Common Containers and Collections. Example:


Stack, List, Queue Etc.

 System.IO: It provides Read and Writing Functions to the Programmer. Which is


used for all types of Input and Output.

 System.Configuration: It provides functions and methods to handle configuration


data.

 System.Data: This database provides related functions and methods. Also known as
ADO.Net.

 System. Drawing: It is used for Graphical Designing Functions and Methods. It is


used in various methods like DrawRectangle, DrawCircle, Pen, Brush etc. Provide
provides.

 System.Windows: This class is used for all Windows Operating System related
Functions and Methods.

 System. Windows. Forms: It is used for all Controls, Methods and Functions of
Windows Forms.

Q 9. Write the execution process of .NET.

Ans. Code Execution Process- The Code Execution Process involves the following two
stages:

1. Compiler time
process.
2. Runtime process.

1. Compiler time process

1. The .Net framework


has one or more
language compliers,
such as Visual Basic,
C#, Visual C++, JScript, or one of many third-party compilers such as an Eiffel, Perl,
or COBOL compiler.
2. Any one of the compilers translate your source code into Microsoft Intermediate
Language (MSIL) code.
3. For example, if you are using the C# programming language to develop an
application, when you compile the application, the C# language compiler will convert
your source code into Microsoft Intermediate Language (MSIL) code.
4. In short, VB.NET, C# and other language compilers generate MSIL code. (In other
words, compiling translates your source code into MSIL and generates the required
metadata.)
5. Currently "Microsoft Intermediate Language" (MSIL) code is also known as
"Intermediate Language" (IL) Code or "Common Intermediate Language" (CIL)
Code.

SOURCE CODE -----.NET COMLIPER------> BYTE CODE (MSIL + META DATA)

2. Runtime process.

1. The Common Language Runtime (CLR) includes a JIT compiler for converting MSIL
to native code.
2. The JIT Compiler in CLR converts the MSIL code into native machine code that is
then executed by the OS.
3. During the runtime of a program the "Just in Time" (JIT) compiler of the Common
Language Runtime (CLR) uses the Metadata and converts Microsoft Intermediate
Language (MSIL) into native code.

BYTE CODE (MSIL + META DATA) ----- Just-In-Time (JIT) compiler------> NATIVE CODE

Q 10. Differentiate between Namespace and Assembly. Or What do you


understand by Namespace and Assembly?

Ans. .Net Namespace provides the fundamental unit of logical code grouping while an
assembly provides a fundamental unit of physical code grouping.

Namespace

Namespaces is a logical group of related classes that can be used by any other language
targeting the Microsoft .Net framework. It is more used for logical organization of your
classes. Namespaces are a way of grouping type names and reducing the chance of name
collisions.

Hierarchy and Fully-Qualified Names

The fully qualified name of a class is constructed by concatenating the names of all the
namespaces that contain the type. For example, the fully qualified name of the TextBox
class is System.Windows.Forms.TextBox. That means TextBox class is contained in the
Forms namespace that is contained in the Windows namespace that is contained in the root
System namespace.

Textbox namespace Hierarchy

Assembly

An assembly is a collection of types and resources that are built to work together and form a
logical unit of functionality. It is an Output Unit, that is .exe or .dll file. It is a unit of
Deployment and a unit of versioning and also it contains MSIL (Microsoft Intermediate
Language) code. Assemblies are self-describing, it contains all the metadata about the
modules, types, and other elements in the form of a manifest.
Assemblies are of two types: Private and Shared Assemblies.

Private Assemblies

Private assembly is intended only for one application. The files of that assembly must be
placed in the same folder of the application.

Shared Assemblies

Shared assembly is to be made into a Shared Assembly, then the naming conventions are
very strict since it has to be unique across the entire system

Q 11. How to force Garbage Collection?

Ans. GC.Collect()Memory management is a primary thing for any application. The .Net
Framework provides a new mechanism for releasing unreferenced objects from the memory,
this process is called Garbage Collection (GC). In some rare situations, forcing a Garbage
Collection may improve your application's performance. The garbage collection (GC)class
provides a GC.Collect method, which you can use to give your application some direct
control over the garbage collector. It might be appropriate to use the GC.Collect method in a
situation where there is a significant reduction in the amount of memory being used at a
defined point in your application's code.
GC.Collect call is discouraged because it decreases the current performance of the
application. Whenever you call the garbage collector to performs a collection, it suspends all
currently executing threads. This can become a performance issue if you call GC.Collect
more often than is necessary. You should be careful not to place code that calls GC.Collect
at a point in your program where users could call it frequently. However, if you can reliably
test your code to confirm that calling Collect () won't have a negative impact then go ahead.
It is not guaranteed that the Garbage Collection process will start after calling the method
and the memory is release. So, there is still uncertainty whether actually the Garbage
Collection will occur or not.
.Net Garbage Collection
The .Net Framework provides a new mechanism for releasing unreferenced objects from the
memory (that is we no longer needed that objects in the program) ,this process is called
Garbage Collection (GC). 
When a program creates an Object, the Object takes up the memory. Later when the
program has no more references to that Object, the Object's memory becomes unreachable,
but it is not immediately freed.
The Garbage Collection checks to see if there are any Objects in the heap that are no longer
being used by the application. If such Objects exist, then the memory used by these Objects
can be reclaimed. So these unreferenced Objects should be removed from memory, then
the other new Objects you create can find a place in the Heap.
Finalization allows a resource to clean up after itself when it is being collected. This
releasing of unreferenced Objects is happening automatically in .Net languages by the
Garbage Collector (GC). The programming languages like C++, programmers are
responsible for allocating memory for Objects they created in the application and reclaiming
the memory when that Object is no longer needed for the program. In .Net languages there
is a facility that we can call Garbage Collector (GC) explicitly in the program by calling
System.GC.Collect.
Garbage collector of .NET tries to compact the memory in such a way as to increase the
working space required for heap. The class GC of .NET class library controls the garbage
collector. The core task of performing a collection is executed by the GC’s optimizing engine
that determines the best time to perform collection based on allocations being made. GC
runs are non-deterministic since the call to GC cannot be guaranteed. However, explicit calls
to the overloaded 'Collect()' method of the class GC can be used whenever needed.
The advantages that GC provides include:

 the elimination of memory de-allocation code in applications

 optimized memory usage in managed heap

 clearing up of memory of reclaimed objects that are no longer in use (which helps to
initialize managed objects allocated in future and provision of memory safety of
objects to avoid an object using content of another.)
Unit II
Programming with .NET Framework

Q 1. Discuss about Windows Form in VB.NET.

Ans. Windows form- It is a graphical application programming interface i.e. it is a GUI


component used for GUI in windows. All windows that are displayed in Windows are called
windows form in the programming. form is a control used to provide windows interface in
.Net. This control acts as a container for other windows controls. In this, by placing all the
controls of windows, User Interface is prepared for windows applications. The window that is
displayed when running the programs of Visual Basic is called form in design time.
The user does not have to work hard to create the form. It provides built in functionality. The
form designer window is used to design the form. Which is the main component of the visual
studio IDE.
The Windows form has the title bar of the form, work area and border in which the title bar
has the Form Icon, Form’s Title, Control box with buttons to maximize, minimize and close.
For this, windows form has properties like controlbox, icon, text etc. The work area is the
place where the user designs and designs the form.
Properties of Windows Form

 Name: form is used to identify the form when writing name codes. It can only be
changed at design time.

Msgbox (Me.Name)

 Text: It is used to get or set the title to be displayed in the title bar of the property
form.

Me.Text = "Windows Form"

 AcceptButton: This property is used to set the default of any button available in the
form, which automatically clicks on pressing the ENTER key.

Me.AcceptButton = Button1

 CancelButton: This property is used to default set any button available in the form,
which automatically clicks on pressing Esc key.

Me.AcceptButton = Button2

 AutoScroll: When this property is ture, the size of the form is less than available
controls to automatically display the scrollbar.

Me.AutoScroll = True
 BorderStyle: This property is used to set the border style of the form. It has the
following values:

1. Sizable: Default, re-sizable window


2. None: Border less window can not resize
3. Fixed: window with visual border but pronounced resize
4. Fixeddialog: a fixed size dialog box
5. FixedSingle: fixed window with single line border
6. FixedToolWindow: contain only close button just like toolbox and further resize
7. SizableToolWindow: contains only close button just like toolbox and can resize.

 ControlBox: This property is used to display or hide the control box (Maximize,
Minimize and close button). It will be displayed when it is true and hide if it is false.

 Minimizebox / MaximizeBox: minimizebox / maximizebox display / enable when it is


true.

 Minimum Size / Maximum Size: This property is used to set the minimum size and
maximum size of the form. It has two sub properties height and width.

 Size: This property is used to get or set the size of the form. It has two sub-properties
height and width.

 StartupPosition: It is used to set the initial position when the form is run.

 BackColor: It is used to set or get the background color of the form.

 BackgroundImage: This is done to set or get the image in the background of the
form.

 Font: It is used to get or set a font.

 ForeColor: It is used to set or get the font color of the form.

Q 2. Discuss about the introduction of Visual Studio.

Microsoft Visual Studio is Microsoft's Integrated Development Environment (IDE). Which


provides the development environment for the languages developed by Microsoft. Its work is
to provide all the necessary tools for program development. It is used to create console and
graphical user interface applications. By this windows form applications, web applications,
websites, console applications etc. can be created. It provides a common IDE for all
languages of .Net in which programs can be created for all its languages. It helps to develop
applications for all types of platforms like Microsoft Windows, Windows Mobile, Windows CE,
.Net Framework, .Net Compact Framework etc. Visual studio provides all facilities for
creating programs for .Net is important languages like VB.Net, C #, ASP.Net, J # etc.
Microsoft Visual Studio provides several new features for older Visual Basic programmers.
And it also provides all the features for other languages. It includes new features for Visual
Basic programmers such as new compilers, language constructors, new debugging
experience etc. Supports This includes Intelligence filtering, form updates, debugging data
tips etc. features have been added.
Visual Studio's code editor supports many features like Intelligence, code refactoring, auto
complete, auto list of members, auto syntax check, auto quick information. Its IDE Designer
provides different GUI applications according to the designers. Such as Windows form
designer for windows form, Web designer for websites, database designer for database etc.
Visual Studio supports many types of languages. It shows features in IDE according to
different languages. This ASP.NET web applications, XML web services, desktop
applications, mobile applications etc. provides tools to develop. It provides and shares tools
in the same IDE for Visual Basic, Visual C #, Visual J #, Visual C ++.
These are different languages like Visual Basic, Visual C #, Visual J #, Visual C ++, F #, M,
Python, Ruby, ASP, XML, HTML, XHTML, DHTML, CSS, Java Script etc. Supports Apart
from this, it also supports other languages.
Versions of Visual Studio and .Net

Releasing
Version Release with
date

.Net 1.0 13-02-2002 Visual Studio.Net

.Net 1.1 24-04-2003 Visual Studio.Net 2003, Windows Server 2003

.Net 2.0 07-11-2005 Visual Studio 2005, Windows Server 2003 R2

.Net 3.0 06-11-2006 Windows Vista, Windows Server 2008

Visual Studio 2008, Windows 7, Windows Server


.Net 3.5 19-11-2007
2008 R2

.Net 4.0 12-04-2010 Visual Studio 2010

Q 3. How to Create Project in VB.Net? or Write down the steps to create a


VB.Net solution

Ans.Following are the steps to create a project in VB.Net.


1. To create a new project in VB.NET, click on the New Sub-menu under File menu.

13. From which the 'New Project Dialog Box' is displayed.

14. From the Type of Project displayed in this window, we select the project that we
want to create. Some of these project types are Visual Basic Projects, Visual C ++
Projects, Visual C # Projects, etc. Each of these project types has different
applications; For example, from Visual Basic Project Type we can create Window
Application, Console Application etc.
15. In this window we will design the form according to our requirement.

Visual Basic Dot Net projects have different types of Templates, which are as follows –

 Windows application  ASP.NET Web Services

 Class library  Web control library

 Windows control library  Console application

 Smart device application  Windows services

 ASP.NET Web Application  Empty project

 ASP.NET Mobile Web Application  Empty web project

Q 4. Explain the IDE (Integrated Development Environment) of VB.NET

IDE (Integrated development environment)IDE is a development environment that helps


develop programs in any language. It provides the program to create and run and all the
features related to it. For example, a window of C or C ++ helps them to develop their
programs and run them. Just as Photoshop's window photo editing tool provides, MS Word's
window documents provide related tools, similarly the language IDE provides all the tools
associated with the program.

 Menu Bar  Toolbar


 Solution Explorer  Code Window

 Toolbox  Object Browser

 Form Designer  Output Window

 Properties Window

Q 5. Describe the Components of Visual Studio.

The Visual Basic IDE (Visual Studio) provides the following components.

 Menu Bar  Properties Window

 Toolbar  Code Window

 Solution Explorer  Object Browser

 Toolbox  Output Window

 Form Designer

Menu Bar

The Visual Basic IDE provides the following Menu.

1. File:File Menu provides facility to create new project, save and open project, add
project, etc.
16. Edit: It provides Basic Editing Tools. Such as Cut, Copy, Paste, Find, Replace,
Undo, Redo, Delete etc.
17. View: This Contains the Commands of Displaying Menu IDE to Windows. Such as
Solution Explorer, Designer, Code Window etc.
18. Project: This gives the command to add new items to the Menu Project.
19. Build: This gives the command to build the Menu Project.
20. Debug: This gives the command for menu debugging.
21. Data: It does the Command Container associated with the Menu Database.
22. Tool: Contains Extra Tools of Menu.Net. Such as Connect To Server, Connect To
Device etc.
23. Window: This Contains Window Arrangement Command like Tile, Cascade etc.
24. Help: Contains the command associated with Help. This menu has the facility of
Online and Offline Help.

Toolbar

The toolbar shows the shortcut of


Commands provided in Menus. There
are several types of toolbar's found in the Visual Studio IDE. Which are used to perform
different types of tasks. In this, the Standard Toolbar contains commands to Create Project,
Save, Open, Editing Commands (Cut, Copy, Paste Etc.), Execute Program. Apart from this,
there are also special toolbar's like Debug, Formatting, Build etc.

SolutionExplorer

It is an important part of the IDE. It


shows the list of all files used in any
project created in .Net. Projects
created in Visual Studio are part of a
Solution. Solution is a collection of all
Projects in the same way as the project
is a collection of all the files used in the
program. In Explorer, Solution Explorer
lists all the files used, therefore it is called Solution Explorer. It is similar to Windows
Explorer. It allows to easily access all the files of the project.
At the top of the Solution Explorer is a toolbar containing some Buttons Display followed by
Solution, Project and its files in Hierarchical form. Its toolbar mainly consists of 6 Buttons -
Properties, Show All Files, Refresh, Class Diagram, View Designer and View Code. It
changes according to Buttons Selected Object. After this the name of the solution appears.
After this, Project and then related files appear. Solution Explorer helps to Arrange and
Access all these files. Any file you see in Solution Explorer can be selected and opened.
When you right click on the file that appears in it, many options associated with the file
appear in the Context menu that appears.
Such as - View Design, View Code, Cut, Copy, Paste, Remove, Delete, Load, Unload, Set
As Startup, Properties, Refresh etc. | Open it by going to the View menu, pressing Solution
Explorer Command or Ctrl + W + S Key. can go.

Toolbox

The toolbox is an important part of the Visual Studio


(Visual Basic) IDE. It helps in designing User Interface.
This shows Window Tools called Windows Control. It
provides the facility to use Windows Controls in Windows
Form by supporting the Drag & Drop Method.
The Toolbox contains all types of Controls used in
Windows. To show the toolbox, click on the toolbox in the
View menu, or can also be shown by the Ctrl + W + X
Shortcut key. Due to the large number of controls in the
toolbox, it is divided into categories. All Categories
contain different types of Controls. The user can click on
these categories to show or hide them. Forms can be
designed by double click or drag on the controls displayed in the toolbox. In this, both the
names of Controls and their Icon are visible.
Some Windows Controls are as follows.

 Common Windows Controls: Button, Textbox, Label, Checkbox, Combo Box, List


Box, Link Label, Picture Box, Radio Button Etc.

 Data: Dataset, Data Grid, Table Adapter Etc.

 Containers: Group Box, Panel Etc.

 Menu & Toolbar: Menu, Toolbar, Status Bar Etc.

Form Designer

Designers hold an important place in Visual Studio.


These designers help in creating GUI. Visual Studio
has many types of designers such as Windows
Form Designer, Web Form Designer, Database
Designer Etc. Windows Form Designer helps in
designing Windows Forms. It is used to create a
User Interface for Windows. In this, a form appears
in which all parts of the form are visible such as Title
Bar, Control Box, Icon Etc. This can be changed by
resizing the form. Controls can be added with the
help of Drag & Drop and they can be moved and
arranged. In this, codes cannot be written for them without using Controls. To display
Windows Forms, use the View Menu, Solution Explorer or Shift + F7 Key.

Properties Window

Properties Window is most commonly used in


Visual Studio. This is a main part of the Visual
Studio IDE. It is used to view and modify the
properties of any object used in Visual Studio
and Projects. In this, the property of Windows
Form, Controls used in it, Project Files,
Database Files and all types of Files are
visible. The Properties window can be viewed
by pressing the View Menu or Ctrl + W + P
key. It displays different types of Editing Fields
for different properties.
At the top of it is a Combo Box, in which the name and type of any selected object is visible.
After that there are buttons in its toolbar which is as follows.

 Categorized: It is used to see Button Properties in Categories.

 Alphabetical: It is used to view properties in Alphabetical Order.

 Properties: It is used to view the list of properties.

 Event: It is used to view the List of Events.

 Properties Page: It is used to view the properties page.

After these Buttons the Properties Window is divided into 3 parts. Which are as follows.

 Property Pan: A list of properties appears in it.

 Value Pan: It shows the


value of properties which
can be changed.

 Description Pan: It has a


short description of the
selected property.

Code Window

Coding is the most important part


of any programming language.
Programs cannot be created
without writing codes in any
language. This feature provides
Code Window in Visual Studio. Codes for all languages can be written for .Net in the Visual
Studio Code Window. Its code varies according to the window program. The Code Window
of Visual Basic supports all types of Visual Basic Features. To display the Code window,
select Code in the View Menu, or Solution Explorer's View Code or Context Menu, in the
Form's Context Menu.
The Code Window of Visual Basic consists of 2 Combo Box (Drop Down List) and a Text
Editor. In this, the first Combo shows the Box Form and the name of the Controls used in
it, in which the Controls can be selected. The events of Control selected in the second
Combo Box are visible, which can be selected and written in Text Editor. The Code Editor
of Visual Basic supports all Coding Features of Visual Basic. Such as - Auto Complete, Auto
List Of Members, Auto Syntax Check, Auto Quick Information, Code Refactoring, Rapid
Application Development (Less Coding) Etc.
Object Browser

Object Browser occupies an important place in Visual Studio. It uses components used in
.Net such as Classes, Namespaces, Enumerators, Interfaces Etc. Shows the. Object
Browser is used to view the properties, events and methods of .Net classes. The Object
Browser or Ctrl + W + J Shortcut Key is used in the View menu to make it appear in the IDE.
On top of this, there is a facility to search for objects. It is mainly divided into three parts.
1. Object Pan: This pan contains a hierarchical list of .Net's Namespaces, Interfaces
and Classes that can be explored. When you explore it, you get a list of classes.
2. Member Pan: In this Pan, the list of members of the class selected in
Object Pan appears. Which mainly consists of properties, events and
methods that can be selected.
3. Description Pan: This Pan contains the description of the selected object
or its member in the Member and Object Pan.

Output Window

The Output Window is also a window of the Visual Studio IDE that displays the messages
generated when programs are compiled and run. In this, the messages are generated when
the program is Build and Run. To show it in the IDE, use the Output Window or Ctrl + W + O
Shortcut key in the View menu. It has a toolbar which contains tools to view messages.
Like- Search, Next, Previous etc. After this all the message displays are in a box.

Q 6. Differentiate between static and constant. Or What are a variable and


constant?

Ans. variable, its value can be changed by the program at runtime. The accessibility or the
scope of a variable refers to where the variable can be read from or written to, and its
lifetime, or how long it stays in the computer memory.e.g. int i;

Constant

A Constant is something that will always remain the same though out the entire lifetime of a
program. A Constant variable cannot be modified after it defines and it cannot be change
throughout the program. The Constant with a fixed value tells the compiler to prevent the
programmer from modifying it. Whenever you try to change it, it will throw an error message.
Constant variables declare with const keyword and can be used with primitive data types.
Constants are set at compile time itself and assigned for value types only. e.g. public const
double PI = 3.14159;

Static

Static variable is a property of a Class rather than the instance of class. It is stored on the
data segment area of memory and the same value is get shared to all instances of that
class. It can be assigned for reference types and set at run time. The static modifier can be
applied with classes, fields, methods, properties, operators, events and constructors. It
represents a kind of a global value for all the instances of that class and can able to call
them using class name.
Product.price = 100;
Where Product is class name and price is a static declaration.

Q 7. How to declare variable in VB.Net?

Ans. A variable is a named location in computer’s memory. When we declare a variable,


compiler allocates fixed bytes of memory to that variable at compile time and assigns a
name to that allocated memory space. A variable is used to store data temporary during
execution of the program. A Variable has a name and value of specific type. One important
characteristic of variable is that the value of variable may change during execution of the
program.

Rules for naming variable in VB.NET

1. Variable name may consist of digits (0-9), Alphabets (A-Z, a-z) and underscore
symbol.
2. Variable name can not contain any special symbols.
3. Reserved words or key words can not be used as a name of variable.
4. The length of variable must not exceed 255 characters.
5. Variable name can not start with digit.
6. Uppercase and Lowercase letters are different.

How To Declare Variable in VB.NET

Most of the programming languages force the programmer to declare all the variables before
they can be referenced in the program otherwise it will generate a compile time error.
However VB.NET does not forces the programmer to declare variables. It means there is no
need to declare the variables before using it in the program. Variables can be declared in
visual basic using two methods.
(1) Implicit Declaration
(2) Explicit Declaration
By default VB.NET supports explicit variable declaration. However if you wish you can
change default behavior by following steps given below:
Step 1: Select Properties option from Project Menu.
Step 2: Select Compile Option.
Step 3: Select OFF in the Option Explicit Combo Box.
You can also write Option Explicit OFF at starting of code window to turn OFF explicit
variable declaration.

Implicit Variable Declaration

In VB.NET it is not compulsory to declare all the variables in advance before it can be
referenced in the program. You can use the variable directly when it is required. When the
compiler finds a variable that is not declared, it will automatically create a new variable of
type object. This type of technique is known as implicit declaration of variable.
The data type of variables declared using implicit declaration is object by default. You can
store any type of value in this type of variable, the compiler will automatically determines the
type of the variable depending upon the type of the value that is stored in the variable.
Disadvantage of Implicit Declaration:
(1) It will decrease the speed and efficiency of the program because the compiler does not
know in advance which variables are being used in the program and what are the data types
of those variables. The compiler has to allocate memory to every variable when it finds a
new variable.
(2) Typing errors can not be caught using this type of technique because if you make a
typing mistake while writing the name of the variable instead of generating a compile time
error the compiler will create a new variable.
(3) By default the data type of the variables declared using this technique is object which
occupies more memory as compared to specific data type.

Explicit Variable Declaration

By default in VB.NET it is compulsory to declare all the variables in advance before it can be
referenced in the program. You can also declare the variable explicitly before it is referenced
in the program. This type of technique is known as explicit declaration of variable.

Advantage of Explicit Declaration:


(1) It will increase the speed and efficiency of the program because the compiler know in
advance which variables are being used in the program and what are the data types of those
variables.
(2) Typing errors can be easily caught using this type of technique because if you make a
typing mistake while writing the name of the variable the compiler will generate a compile
time error indicating "variable is not defined".
(3) Type Mismatch error can be easily caught using this technique. For example if you
declared a variable of type integer and assign a string value to that variable will generate run
time error indicating "Type Mismatch".
(4) You can declare typed variable using this technique so the memory is allocated
depending upon the type of the variable. Thus there is no wastage of memory space while
declaring variables explicitly.

How To Declare Variable Explicitly?

Variables can be declared explicitly using the Dim statement. The general syntax for
declaring the variable is given below:
Syntax:
Dim variable-name as DataType
Example:
Dim Name as String
When you declare the variable the compiler allocates space for that variable depending upon
the Type of the variable and assigns one name for that reserved memory space. So later in
the program you can refer to that memory space using the name of the variable. We can
also declare more then one variables of the same type in the same line as shown below:
Dim a as integer, b as integer, c as integer
We can also declare more then one variable of different type in the same line as shown
below:
Dim a as Integer, b as String, c as Double

Q 8. What are Data types in VB.Net?

Ans. When a variable is declared, then we also have to write its data type, because the
value to be stored in any variable depends on its data type. The type of data type of the
variable will be the same type. Value store can be done.
DATATYPE in a programming language describes that what type of data a variable can
hold. When we declare a variable, we have to tell the compiler about what type of the data
the variable can hold or which data type the variable belongs to.
Syntax : Dim VariableName as DataType
VariableName : the variable we declare for hold the values.
DataType : The type of data that the variable can hold
In Programming, data types define the type of data. Data types tell the type of data to be
stored as well as its data storage length. The variables in Visual Basic are divided into the
following five categories.

 Numeric

 String

 Boolean

 Date

 Object

1. Numeric Variables: Numbers in which decimal points are not used are called Integer
numbers. It consists of data types that store numbers. They are used to perform
mathematical operations. It contains the following data type’s-

• Short (Int16): It is used to store integer value. In this, the value can be stored from
-32768 to 32767 and it takes 2 bytes in memory.

Dim a as short

a = 10000

• Integer (Int32): It is used to store integer value. In this, the value can be stored
from -2147483648 to 2147483647 and it takes 4 bytes in memory.

Dim a as integer

a = 1000000

• Long (Int64): It is used to store integer value. It can store more value than integer
and it takes 8 bytes in memory.
Integer variables are stored sighned 32 bit integer values in the range of
-2,147,483,648 to +2,147,483,647

 VB.NET Runtime type : System.Int32

 VB.NET declaration : dim count as Integer

 VB.NET Initialization : count = 100

 VB.NET default initialization value : 0

25. Floating point Numbers: Numbers in which decimal points are used, are called
floating point Numbers.
• Single: It stores single precision floating no. It can store values from
-3.402823E38 to -1.401298E-45 and 1.401298E-45 to 3.402823E38. It takes 4
byte memory.
• Double: It stores double precision floating no. It can store values from
-1.797693134486232E308 to -4.94065645841247E-324 and
4.94065645841247E-324 to 1.797693134486232E308. It takes 8 byte memory.
• Decimal: It can store 0 to 7.9228162514264337593543950335 positive and
negative values. It takes 16 Byte in memory.
• Byte: This is also a numeric data type that stores values from 0 to 255. It has 2
byte in memory
26. String: A group of characters is called a string. It is used to store characters. It
consists of the following 2 types.

• String: It is used only to store text. It stores the set of characters. It can store text
up to 2 GB.
• Char: It is used to store single character. And takes 2 byte space in memory.
String variables are stored any number of alphabetic, numerical, and special
characters . Its range from 0 to approximately 2 billion Unicode characters.

 VB.NET Runtime type : System.String

 VB.NET declaration : Dim str As String

 VB.NET Initialization : str = "String Test"

 VB.NET default initialization value : Nothing

27. Boolean: This data type is used to store true or false value. It is mostly used
to check conditions.

Boolean variables are stored 16 bit numbers and it can hold only True or false.

 VB.NET Runtime type : System.Boolean

 VB.NET declaration : dim check as Boolean

 VB.NET Initialization : check = false

 VB.NET default initialization value : false

28. Date: This data type is used to store date and time. In this, use # character to
store the date or time.

Dim a as date
a = # 1/4/2005 #
29. Object: This is a common data type that is used to store all types of values with
common features of all data types.

In VisualBasic.Net we can convert a datatype in two ways. Implicit


Conversion and Explicit conversion. Also we can convert a type value to a reference and
reference value to a type value. These are called Boxing and unBoxing . Boxing referes
value type to reference type and unboxing, reference type ot value type.

Q 9. What do you understand by Variables?

Ans. To process any type of data, we have to first decide what kind of data we want to store
in the memory of the computer, because as long as we store the data to be processed in the
computer's memory If we do not, we cannot process that data.
Since different types of data reserve space of different sizes in memory, when we get to
know the type of data to be processed, then we will be in memory based on the keyword
representing that data type. Some reserve the space and assign a name to that space. This
name is a Symbolic Identifier of the Reserved Memory Location, which is determined based
on the rules of the Identifier Naming Convention.
To store a data based on the need of the program, the process of reserving space in the
memory of the computer and giving a symbolic name of that space is called Identifier
Declaration.
If the value of the identifier to be defined remains constant throughout the program, this
process is called Constant Declaration, whereas if the value of the identifier to be defined
changes from time to time across the program depending on the need of the program, it
Variable Declaration says.
Variables hold a very important place in computer programming. Variables, named locations
that are used to store a value. Each variable has a name and value as well as a Type. There
are many types of data types in visual basic. Such as - Integer, String, Date, Char, Decimal
etc.

The basic value types provided in VB.Net can be categorized as −

Type Example

Integral types SByte, Byte, Short, UShort, Integer, UInteger, Long, ULong and Char

Floating point Single and Double


types

Decimal types Decimal


Boolean types True or False values, as assigned

Date types Date

VB.Net also allows defining other value types of variable like Enum and reference types of
variables like Class.

Declaring Variables

In Visual Basic.Net, the dim statement is used to declare the variable. The following are
Syntax.
Syntax: Dim <Variable Name> As <Data Type>
Example: Dim name As String
In this statement Dim states the dimension of the keyword variable, variable name, variable
name, As keyword and data type. In Visual Basic.Net, variables are usually declared this
way. Also the variable declaration statement changes according to the scope. The public
keyword is used in place of Dim to declare the public variable.

Public <Variable Name> As <Data Type>

Similarly, private and friend keywords are also used to declare variables. private, public,
protected and friend variable are used to scope. Multiple variables can be declared in a
single statement in VB.Net. Example: Dim a, b, c as Integer
Similarly, multiple type variables can also be declared in a single dim statement. Example:
Dim a As Integer, name As String, b As Boolean

Variable Naming Conventions

 Variable's name always starts with a letter.

 Variable name should not always be more than 255 character.

 No other character is used except for numbers and underscore in variable name.

 Variable name should always be unique in its scope.

 Visual Basic keywords cannot be used in Variable name.

 Variable name should not contain blank space.

Q 10. Define various type conversions in Visual Basic

The process of changing a value from one data type to another type is called conversion.
Conversions are either widening or narrowing, depending on the data capacities of the types
involved. They are also implicit or explicit, depending on the syntax in the source code.
Widening and Narrowing Conversions

An important consideration with a type conversion is whether the result of the conversion is
within the range of the destination data type.

A widening conversion changes a value to a data type that can allow for any possible value
of the original data. Widening conversions preserve the source value but can change its
representation. This occurs if you convert from an integral type to Decimal, or
from Char to String. For example, converting a value of type integer to a value of type Long
is a widening conversion because the Long type can accommodate every possible value of
the Integer type. Widening conversions always succeed at run time and never incur data
loss. You can always perform them implicitly, whether the Option Strict Statement sets the
type checking switch to On or to Off.

Narrowing Conversions

A narrowing conversion changes a value to a data type that might not be able to hold some
of the possible values. For example, a fractional value is rounded when it is converted to an
integral type, and a numeric type being converted to Boolean is reduced to
either True or False.

The standard narrowing conversions include the following:

 The reverse directions of the widening conversions in the preceding table (except
that every type widens to itself)

 Conversions in either direction between Boolean and any numeric type

 Conversions from any numeric type to any enumerated type (Enum)

 Conversions in either direction between String and any numeric type, Boolean,


or Date

 Conversions from a data type or object type to a type derived from it

Narrowing conversions do not always succeed at run time, and can fail or incur data loss. An
error occurs if the destination data type cannot receive the value being converted. For
example, a numeric conversion can result in an overflow. The compiler does not allow you to
perform narrowing conversions implicitly unless the Option Strict Statement sets the type
checking switch to Off.

Implicit and Explicit Conversions

An implicit conversion does not require any special syntax in the source code. In the
following example, Visual Basic implicitly converts the value of k to a single-precision
floating-point value before assigning it to q.
Dim k As Integer

Dim q As Double

' Integer widens to Double, so you can do this with Option Strict On.

k = 432

q = k
An explicit conversion uses a type conversion keyword. Visual Basic provides several such
keywords, which coerce an expression in parentheses to the desired data type. These
keywords act like functions, but the compiler generates the code inline, so execution is
slightly faster than with a function call.
In the following extension of the preceding example, the CInt keyword converts the value
of q back to an integer before assigning it to k.

' q had been assigned the value 432 from k.

q = Math.Sqrt(q)

k = CInt(q)

' k now has the value 21 (rounded square root of 432).

Q 11. What is an operator?

Ans. An operator refers to a symbol that instructs the compiler to perform a specific logical
or mathematical manipulation. The operator performs the operation on the provided
operands. Microsoft VB.Net comes with various types of operators.

 Arithmetic Operators  Bit Shift Operators

 Comparison Operators  Assignment Operators

 Logical/Bitwise Operators  Miscellaneous Operators

Arithmetic Operators

You can use arithmetic operators to perform various mathematical operations in VB.NET.
They include:

Symbol Description

^ for raising an operand to the power of another operand

+ for adding two operands.


- for subtracting the second operand from the first operand.

* for multiplying both operands.

/ for dividing an operand against another. It returns a floating point


result.

\ for dividing an operand against another. It returns an integer result.

MOD known as the modulus operator. It returns the remainder after


division.

Comparison Operators

These operators are used for making comparisons between variables. They include the
following:

Comparison Operators Details

= for checking whether the two operands have equal


values or not. If yes, the condition will become true.

<> for checking if the value of the left operand is greater


than that of the right operand. then condition will become
true.

> for checking whether the value of the left operand is less
than that of the right operand. If yes, the condition will
become true.

< for checking whether the value of the left operand is


greater than or equal to that of the right operand. If yes,
the condition will become true.

>= for checking whether the two operands have equal


values or not. If yes, the condition will become true.

<= for checking whether the value of the left operand is less
than or equal to that of the right operand. If yes, the
condition will become true.

Logical/Bitwise Operators

These operators help us in making logical decisions.


They include:

Logical/ Bite wise Operator Descriptions

And known as the logical/bitwise AND. Only true when


both conditions are true.

Or known as the logical/bitwise OR. True when any of


the conditions is true.

Not The logical/bitwise NOT. To reverse operand's logical


state. If true, the condition becomes False and vice
versa.

Xor bitwise Logical Exclusive OR operator. Returns False


if expressions are all True or False. Otherwise, it
returns True.

AndAlso It is also known as the logical AND operator. Only


works with Boolean data by performing short-
circuiting.

OrElse It is also known as the logical OR operator. Only


works with Boolean data by performing short-
circuiting.

IsFalse Determines whether expression evaluates to False.

IsTrue Determines whether expression evaluates to True.

Bit Shift Operators

These operators are used for performing shift operations on binary values.

Bit-shit operatiors Details

And Known as the Bitwise AND Operator. It copies a bit to


result if it is found in both operands.

Or Known as the Binary OR Operator. It copies a bit if found in


either operand.

Xor The Binary XOR Operator. For copying a bit if set in one of
the operands rather than both.

Not It is known as the Binary Ones Complement Operator. It is


a unary operator that 'flips' the bits.

Assignment Operators

Assignment Operator Details

=  the simple assignment operator. It will assign


values from the left side operands to the right side
operands.

+=  known as the Add AND assignment operator. It will


add the right operand to the left operand. Then the
result will be assigned to the left operand.

=  known as the Subtract AND operator. It will


subtract the right operand from left operand and
assign the result to the left operand.

*=  : known as the Multiply AND operator. It will


subtract the right operand from left operand and
assign the result to the left operand.

Miscellaneous Operators

There are other operators supported by VB.NET. Let us discuss them:

Miscellaneous Operators Details

GetType This operator gives the Type of objects for a specified


expression.

Function Expression  for declaring the code and parameters of a


lambda
 expression function.

AddressOf  Returns the address of a procedure

Q 12. What do you understand by Events? Define various kinds of VB.Net


Events.

Ans.One of the very prime features of the visual basic language is that it makes use of the
statements which is used to specify actions. Even when you visualize a visual studio project
as procedural series which are executed in a sequence but in reality, they all form a part of
the events and therefore they are event-driven which means that the flow of execution is
only determined by all the external occurrences happening around which are also called as
events. They are basically user actions such as keypress, mouse-related movements, clicks,
etc. or it is also used for doing some occurrences such as system-oriented and generated
notifications. Also, the applications are also required to respond to all the events whenever
they occur. This includes clicking on a home button or entering some form of a text in the
text box, clicking on the menu item. They all form part of event examples. An event can be
defined to be an action which calls another function or causes another event to get triggered.
Handlers, on the other hand, are functions that tell us how to respond to the event.
Below are the Two types of VB. Net event:

1. Mouse-Based Events
Mouse events occur when the mouse makes any movement in controls or the forms. The
following are some of the mouse-related events which are related to a control class.

1. MouseEnter:This event gets triggered when the pointer of the mouse enters the control.

Syntax:
private sub func_name(alias as Datatype1, alias as Datatype2)Handles
object.MouseEnterProgram BodyEnd Sub
Example:
//defining a subroutinePrivate Sub MouseEnter(sender As ObjectType, e As
EventArguments)Handles abc.MouseEnter//writes the code for handling mouse enter on abc
textboxabc.BackColor = Color.Blueabc.ForeColor = Color.RedEnd Sub
Popular Course in this category
2.MouseDown: This event gets triggered when the mouse button is pressed and the cursor
is brought towards the downside of it.
Syntax:
private sub func_name(alias as Datatype1, alias as Datatype2)
Handles object.MouseDown
Program Body
End Sub
Example:
//defining a subroutine
Private Sub MouseDown(sender As ObjectType, e As EventArguments)
Handles abc.MouseDown
//writes the code for handling mouse down
abc.BackColor = Color.Blue
abc.ForeColor = Color.Red
End Sub
3.MouseUp: This event gets triggered when the mouse pointer is over the control which is
handling it and the already pressed mouse button is released.
Syntax:
private sub func_name(alias as Datatype1, alias as atatype2)
Handles object.MouseUp
Program Body
End Sub
Example:
//defining a subroutine
Private Sub MouseUp(sender As ObjectType, e As EventArguments)
Handles abc.MouseUp
//writes the code for handling mouseUp
abc.BackColor = Color.Blue
abc.ForeColor = Color.Red
End Sub
4.MouseLeave: This is the event that gets triggered when the mouse pointer leaves the
control.
Syntax:
private sub func_name(alias as Datatype1, alias as Datatype2)
Handles object.MouseLeave
Program Body
End Sub
Example:
//defining a subroutine
Private Sub MouseLeave(sender As ObjectType, e As EventArguments)
Handles abc.MouseLeave
//writes the code for handling mouseLeave for abc textbox
abc.BackColor = Color.Blue
abc.ForeColor = Color.Red
End Sub
5. MouseWheel: This event gets triggered when the wheel of the mouse moves and the
control is provided the focus.
Syntax
<element onwheel="mytestScript">
object.onwheel = function(){mytestScript}; object.addEventListener("wheel", mytestScript);
Example:
document.getElementById("DIV").addEventListener("wheel", testFunction);
function testFunction() {this.style.fontSize = "70px";}

2. Keyboard Based Events


These are the events that are triggered when the events are fired upon any action done on
the keyboard. This includes actions such as keypress, keydown, enter, etc. Let us study
some of the keyboard-based events in detail.
1. KeyDown: This event is a keyboard-based trigger that occurs when a key is pressed
towards the downside and the control has focus.
Syntax:
private sub func_name(alias as Datatype1, alias as Datatype2)
Handles object.KeyDown
Program Body
End Sub
Example:
Private Sub KeyDown(sender As Object, e As KeyEventArgs) _
Handles abc.KeyDown
If (KeyDown.IsNumber(Chr(e.KeyCode))) Then
alert.Show("Enter Customer ID number")
abc.Text = " "
End If
End Sub
2. KeyUp: This event is a keyboard-based trigger that occurs when a key is pressed towards
the upside and the control has focus.
Syntax:
private sub func_name(alias as Datatype1, alias as Datatype2)
Handles object.KeyUp
Program Body
End Sub
Example:
Private Sub KeyUp(sender As Object, e As KeyEventArgs) _
Handles abc.KeyUp
If (KeyUp.IsNumber(Chr(e.KeyCode))) Then
alert.Show("Enter Customer ID number")
abc.Text = " "
End If
End Sub
3. KeyPress: This event gets triggered when a particular key is pressed onto the keyboard.
Syntax:
Public Class class_name
private sub func_name(alias as Datatype1, alias as KeyPressArguments)
Handles object.KeyPress
Program Body
End Sub
Example:
Public Class testKeyPress
Private Sub KeyPress(Value sender As System.Object, Value e As
System.Windows.KeyPressEventArguments) Handles abc1.KeyPress
If !(e.KeyChar = Convert.ToChar(10)) Then
MsgBox("key is not pressed ")
End If
End Sub
End Class

Methods

A method is an action that an object can perform. A method is a procedure created as a


member of a class and they cause an object to do something. Methods are used to access
or manipulate the characteristics of an object or a variable. There are mainly two categories
of methods you will use in your classes −

 If you are using a control such as one of those provided by the Toolbox, you can call
any of its public methods. The requirements of such a method depend on the class
being used.

 If none of the existing methods can perform your desired task, you can add a method
to a class.

For example, Add is a method of the ComboBox object, because it adds a new entry to a


combo box.

The following procedure uses the Add method to add a new item to a ComboBox.

Sub AddEntry(newEntry asString)


Combo1.Add newEntry

EndSub
For example, the MessageBox control has a method named Show, which is called in the
code snippet below −
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs)
Handles Button1.Click
MessageBox.Show("Hello, World")
End Sub
End Class

Q 13. Describe Variable’s Scope and Lifetime of a Variable.

The difference between lifetime and scope is quite simple. Lifetime - Refers to how long or
when the variable is valid (i.e. how long will it retain its value for).
Scope - Refers to where the variable can be accessed.The difference between lifetime and
scope is quite simple.lifetime is how long the variable retains its value for.The scope refers to
where the variable can be used.

Variable Lifetime

The lifetime of the local variable "imylocal" extends from the moment ProcedureOne is
entered to the moment ProcedureOne has finished. However, the local variable "imylocal"
still exists when ProcedureTwo is called, it is just out of scope.

Public Sub ProcedureOne()


Dim imylocal As Integer
   imylocal = 5
   Call ProcedureTwo()
   imylocal = 10
End Sub

Public Sub ProcedureTwo()


'do something
End Sub

Variable Scope

Every variable has a scope associated with it. This scope refers to the area of code where
the variables will be recognised. Variables (and constants) have a defined scope within the
program. The scope for a variable can either be: Procedure Level - Also known as a local
variable. Module Level - A private module level variable is visible to only the module it is
declared in. Global Level - A public module level variable is visible to all modules in the
project.
A Variable’s Scope: The scope of a variable is the section of the application that can see
and manipulate the variable. If a variable is declared within a procedure, only the code in the
specific procedure has access to that variable. When the variable’s scope is limited to a
procedure it’s called local.
e.g.
Private Sub Command1_Click()
Dim i as Integer
Dim Sum as Integer
For i=0 to 100 Step 2
Sum = Sum +i
Next
MsgBox “ The Sum is “& Sum
End Sub
A variable whose value is available to all procedures within the same Form or Module are
called Form-wide or Module-wide and can be accessed from within all procedures in a
component.  In some situations, the entire application must access a certain variable. Such
variable must be declared as Public.
Lifetime of a Variable: It is the period for which they retain their value. Variables declared
as Public exist for the lifetime of the application. Local variables, declared within procedures
with the Dim or Private statement, live as long as the procedure.
You can force a local variable to preserve its value between procedure calls with the Static
keyword. The advantage of using static variables is that they help you minimize the number
of total variables in the application.
Variables declared in a Form outside any procedure take effect when the Form is loaded and
cease to exist when the Form is unloaded. If the Form is loaded again, its variables are
initialized, as if it’s being loaded for the first time.

Q 14. How to create enumeration in VB.Net?

Ans.You create an enumeration with the Enum statement in the declarations section of a


class or module. You cannot declare an enumeration within a method. To specify the
appropriate level of access, use Private, Protected, Friend, or Public.

An Enum type has a name, an underlying type, and a set of fields, each representing a
constant. The name must be a valid Visual Basic .NET qualifier. The underlying type must
be one of the integer types—Byte, Short, Long or Integer. Integer is the default.
Enumerations are always strongly typed and are not interchangeable with integer number
types.
Enumerations cannot have floating-point values. If an enumeration is assigned a floating-
point value with Option Strict On, a compiler error results. If Option Strict is Off, the
value is automatically converted to the Enum type.

To declare an enumeration

1. Write a declaration that includes a code access level, the Enum keyword, and a valid
name, as in the following examples, each of which declares a different Enum.

PrivateEnum SampleEnum
SampleMember
EndEnum
PublicEnum SampleEnum2
SampleMember
EndEnum
ProtectedEnum SampleEnum3
SampleMember
EndEnum
FriendEnum SampleEnum4
SampleMember
EndEnum
ProtectedFriendEnum SampleEnum5
SampleMember
EndEnum
30. Define the constants in the enumeration. By default, the first constant in an
enumeration is initialized to 0, and subsequent constants are initialized to a value of
one more than the previous constant. For example, the following enumeration, Days,
contains a constant named Sunday with the value 0, a constant named Monday with
the value 1, a constant named Tuesday with the value of 2, and so on.

PublicEnum Days
Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
EndEnum
31. You can explicitly assign values to constants in an enumeration by using an
assignment statement. You can assign any integer value, including negative
numbers. For example, you may want constants with values less than zero to
represent error conditions. In the following enumeration, the constant Invalid is
explicitly assigned the value –1, and the constant Sunday is assigned the value 0.
Because it is the first constant in the enumeration, Saturday is also initialized to the
value 0. The value of Monday is 1 (one more than the value of Sunday); the value
of Tuesday is 2, and so on.

PublicEnum WorkDays
Saturday
Sunday = 0
Monday
Tuesday
Wednesday
Thursday
Friday
Invalid = -1
EndEnum

To declare an enumeration as an explicit type

 Specify the type of the enum by using the As clause, as shown in the following
example.

PublicEnum MyEnum AsByte


Zero
One
Two
EndEnum
Unit III
Control Structure

Q 1. What do you understand by Control structure in VB.Net?

Ans. Control structures enable programmers to control the order of events in their programs.
Visual Basic's sequence, selection and repetition structures are used to select and repeat
various statements and thereby execute complex algorithms. In the process, we introduce
commonly used shorthand operators that allow the programmer quickly to calculate and
assign new values to variables. Normally, statements in a program are executed one after
another in the order in which they are written. This process is called sequential execution.
However, various Visual Basic statements enable the programmer to specify that the next
statement to be executed might not be the next one in sequence. A transfer of control occurs
when a statement other than the next one in the program executes.
Visual Basic provides seven types of repetition structures: While, DoWhile/Loop,

Do/LoopWhile, DoUntil/Loop, Do/LoopUntil, For/Next and ForEach/Next. (ForEach/Next is
covered in Chapter The control flow in VB.Net controls the flow of statements program. It
controls the data used in the program. These statements are of two types.
The words If, Then, Else, End, Select, Case, While, Do, Until, Loop, For, Next and Each are
all Visual Basic keywords.

 Conditional Statements

 Looping Statements

Conditional Statements: In VB.Net conditional statements are used to check the


conditions. It is mainly of three types.
• If- Then
• If - Then - Else
• Select Case
If- then

The if-then statement is used to check normal conditions. If the condition written in it is
true, the statements of If- End If block are executed. And the control goes out when the
condition is false.
Syntax:
If Condition Then
Statements
End If
Example:
If a> b Then
Msgbox ("A is greater")
End If

If- then- else

This conditional statement consists of two blocks. An If block is executed when the
condition is true and an Else block is executed when the condition is false.
Syntax:
If Condition Then
[If block states]
Else
[Else Block Statements]
End If
Example:
If a> b Then
Msgbox ("A is greater")
Else
Msgbox ("B is greater")
End If

Select case

The Select Case statement is used to check the value of an expression on different
cases. In this, the expression written in select case is matched with value cases and if
the correct match is found, the statement of that block is executed. If a case does not
match, the case Else statement is executed.
Syntax:
Select Case textexpression
Case ExpressionList ……… N
[‘Statements…… N]]
[Case Else
[Statement Else]]
End select
Example:
Select Case Now.DayOfWeek
Case DayOfWeek.Sunday
MsgBox ("Its Time to Enjoy")
Case DayOfWeek.Monday
MsgBox ("Have a nice week")
Case else
MsgBox ("Enjoy this week")
End select
Select case

Looping Statements in VB.Net

Looping statements are used to repeat a code or task multiple times. These statements
repeatedly repeat the task according to a condition. There are mainly three types of looping
statements in VB.Net.
• For-Next
• While- End While
• Do- Loop

For-next

This looping statement is a popular looping statement. It is used to repeatedly execute


statements in a series according to a loop index.
Syntax:
For counter = start to end [Step increment / decrements]
[Statements]
[Exit For]
[Statements]
Next [counter]
Where counter is a variable, start and end denote the starting and ending point of the
loop. The step is used for more than 1 increment / Decrements. Exit For statement is
used to stop the for loop in between.
Example:
For i = 0 To 10 Step 2
MsgBox (i)
Next

While- End While

It is used to run the loop according to the loop condition. In this loop, a condition is
defined by which looping statements are executed when true and it is exited directly
when false. Following is its syntax.
Syntax:
While Condition
[Statements]
[Exit while]
[Statements]
End While
Exit while is used to break the while loop.
Example:
Dim i As Integer = 0
While i <= 10
MsgBox (i)
End While
Do-loop
It is similar to loop while loop. It is used to repeat a statement for indefinite time. do
loop executes the statement until the condition written in while or until becomes false.
In this, two keywords while and until are used. It has an exit do statement which is
used to break the loop in between. Following is the syntax of this loop.
Syntax:
Do {[While / until] condition}
[Statements]
[Exit Do]
[Statements]
Loop {[While / until] condition}

Q 2. What do you understand by Array?

Ans. When we have to access and manipulate a program by storing a lot of data of the
same type, then instead of declaring many Variables to store these same types of data, we
do Array Declare.
Array is a type of Reference Type that uses the Heap Area of Memory to store the same
type of Data Items and uses Continues Memory Locations to store every Data Item of Array.
All data items are stored in memory in a fixed order and a unique Zero Based Unique Index
Number is specified with each element to uniquely identify it. Also, Array is a Fixed Data
Structure. So once the Array's size is defined, then the Array's size cannot be modified.
Declaring Array: Array, like Simple Variable, is given the value of the last index of the array
in parentheses (parentheses) after the name of the array while Declare using Dim, Private or
Public Statement. Which is called subscript, index or size.
Syntax: Dim <array name> (subscript) As <Data Type>
Example: Dim employee_ name (20) As String
Dim salary (20) As Integer
Types of Array
There are two types of Array in Visual Basic.
1. One Dimensional Array
32. Multi-Dimensional Array

1.One Dimensional Array: An array containing only one index or subscript is called a
dimensional array. Multiple values can be stored in it. In this, its index is used to store or
access a value in an array.
Example: Dim marks (10) As Integer
The marks array can store 0 to 9 indexes or 10 values in the marks array.
• Initializing one dimensional Array: values can be inserted in both the design and run time in
a dimensional array.
Array index or Curly brackets {} are used to store the value in design time.
Syntax: Dim array_name () As DataType = {element1, element2,….}
Example: Dim name () As String = {"Raj", "Shyam", "Ashu"}
or
Dim Name (2) As String
Name (0) = "Raj"
Name (1) = "Shyam"
Name (2) = "Ashu"
2. Multi-Dimensional Array: Arrays of many dimensions can be created in VB.Net. Arrays
that contain more than one subscripts are called multi-dimensional arrays. Dim, private or
public statements are also used to declare multi-Dimensional arrays. When declare it more
than one subscripts are given in it. It can store values equal to multiple of subscripts such
that n (2,3) array can store 6 values.
• Syntax: Dim <array name> (script1, script2…) As <Data Type>
• Example: Dim matrix (3, 3) as Integer
Dim T (2, 3, 4, 2) As Double
• Initializing Multi-Dimensional Array: Use Curly brackets to initialize Multi-Dimensional
Array.
Dim n (3, 3) As Integer = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}

In visual basic, Method is a separate code block and that will contain a series of statements
to perform particular operations.

Q 3. What is method in VB.Net?

Ans. Generally, in visual basic Methods are useful to improve the code reusability by
reducing the code duplication. Suppose, if we have the same functionality to perform in
multiple places, then we can create one method with required functionality and use it
wherever it is required in the application.A method is a unit of functionality, an operation,
within a class or an object. Programs comprise multiple methods, organized in objects, and
accordingly combined to solve a particular problem. As any dictionary will tell you, a method
is simply a way of doing something. In OOP, methods are the way we do things with
procedures and functions.
You can think of the term routine as a noun used to refer collectively to procedures and
functions in structure−oriented languages like generic Pascal and BASIC, while method is
the collective noun in OOP.
Procedures are known as Sub methods in Visual Basic (short for subroutine) and do not
return a value. To return a value, you use a Function method. Both method types,
respectively, are demonstrated as follows:
'A Sub method
Sub MyMethod()
'Make hay . . .
End Sub
'A Function method
Function MyMethod()As Integer
'Make hay and return the amount made
Return amount 'or
Return MyMethod 'or
MyMethod = Amount
End Sub
Syntax of Visual Basic Methods

In visual basic, we can create the Methods either by using Sub or Function keywords like as


shown below. If we create a method with Sub keyword that will not allow us to return any
value. In case, if you want to return any value, then you need to use Function keyword to
create the method.
<Access_Specifier> Sub Method_Name(<Parameters>)
    ' Statements to Execute
End Sub
 Or
 <Access_Specifier> Function Method_Name(<Parameters>) As <Return_Type>
    ' Statements to Execute
    Return return_val
End Function
If you observe the above syntax, we can create a method either by using Sub or Function
keyword based on our requirements.
Following table lists the parameter details which we specified while creating the methods.

 Parameter Description

Access_Specifie It is useful to define an access level either public or private, etc. to


r allow other classes to access the method. If we didn’t mention any
access modifier, then by default it is private.

Method_Name It must be a unique name to identify the method.

Parameters The method parameters are useful to send or receive a data from
method and these are enclosed within parentheses and are
separated by commas. In case, if no parameters are required for a
method then, we need to define a method with empty parentheses.

Return_Type It is useful to specify the type of value the method can return.

Q 4. What are the types of method?

AnsTypes of MethodsThe generally accepted style for organizing methods in classes is to


categorize them into two groups:
Accessor methods An accessor method (often called a "get method") is used to access
information from another object or a local field in the current object and it does not
manipulate the object or change its data in any way. An example of an accessor method is
one that would allow us to query the current state of an object. Accessor methods are also
often used to perform calculations and compute data.
Modification methods A modification method (often called a "set method") lets you
manipulate an object and change its data. It can be designed to compute values, perform
calculations, interact with external objects, and ultimately change the specific state of an
object, values in variable fields, and so on. An object might have an "on" condition, for
example, and you could use the modification method to set the condition to off.

Q 5. How can method get the data?

Ans. Methods typically need to be provided with data (values or references to values) to
process when they are called or contacted. They can get this data from four places:

 Class−level global data, or data the method can see elsewhere in the class

 Data from external classes and objects

 Method−level data (inside the method or within method blocks)

 Data passed to a method via its parameter list. Parameter fields expose data to the
method.

Class−level data is data stored in the variable and constant fields, or within properties, which
are scoped to the class. The following code shows a simple method accessing class−level
data:
Public Class Calcs
Const C As Integer = 186355 'mps
Dim warp As Integer = 5
Public Function FactorLightSpeed() As Integer
Return C \ warp
End Function
End Class
Data from external objects or classes is data that is explicitly made available to calling
methods. Such data is usually provided from properties, fields, or return values from
methods that exist in an object with which the calling method is associated. In the following
example, the calling method uses the data received from a specialist object to continue with
its calculations:
Public Class Calcs
Const C As Integer = 186355 'mps
Public Function FactorLightSpeed() As Integer
Method−level data is data in variable or constant fields that is scoped local to the method or
any block nested inside the method. Such data is the most encapsulated data in an object
because only the method in which the variables or constants are declared has direct access
to the data. The following example shows variables and constants declared inside the
method:
Public Class Calcs
Const C As Integer = 186355 'mps
Public Function FactorLightSpeed() As Integer
Const C As Integer = 186355 'mps
Dim warp As Integer = 5
Return C \ warp
End Function
End Class
Visual Basic allows you to declare method−level static variables that have values that
survive the termination of the method. In other words, the static variable is not disposed of
with the destruction of the method call that comes after its completion. In the following
example, a static method retains its value after the execution steps exit the method:
Public Class Complex
Public Function FactorLightSpeed() As Integer
Const C As Integer = 186355 'mps
Static warp As Long = 5
Return C \ warp
End Function
End Class
The ability to pass data to a method in this fashion is the most powerful option you have for
making data available to the method. It is also the most dynamic, soft−coded way. The caller
or sender of the message maintains the utmost control over the data that is sent as an
argument to the method's parameter. The method is also able to tightly control the data that
it receives, because it can perform checks on the inbound references or values and take action
accordingly. It can perform such checks in a number of ways, which includes specifying the type
required, a built−in strong typing filter. The level of method coupling varies in the previous four key
options for providing data to the method. The highest level of coupling between methods results from
the class level or global variables, while the lowest level of coupling is achieved when data is
explicitly sent to the method via its formal parameter list.

Q 6. Differentiate between functions and sub procedure.

Ans.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
Example
Following code snippet shows a function FindMax that takes two integer values and returns
the larger of the two.

FunctionFindMax(ByVal num1 AsInteger,ByVal num2 AsInteger)AsInteger


' local variable declaration */
Dim result As Integer

If (num1 > num2) Then


result = num1
Else
result = num2
End If
FindMax = result
End Function

Function Returning a Value

In VB.Net, a function can return a value to the calling code in two ways −

 By using the return statement

 By assigning the value to the function name

The following example demonstrates using the FindMax function −

Module myfunctions
FunctionFindMax(ByVal num1 AsInteger,ByVal num2 AsInteger)AsInteger
' local variable declaration */
Dim result As Integer

If (num1 > num2) Then


result = num1
Else
result = num2
End If
FindMax = result
End Function
Sub Main()
Dim a As Integer = 100
Dim b As Integer = 200
Dim res As Integer

res = FindMax(a, b)
Console.WriteLine("Max value is : {0}", res)
Console.ReadLine()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
Max value is : 200
Recursive Function
A function can call itself. This is known as recursion. Following is an example that calculates
factorial for a given number using a recursive function −

Module myfunctions
Function factorial(ByVal num AsInteger)AsInteger
' local variable declaration */
Dim result As Integer

If (num = 1) Then
Return 1
Else
result = factorial(num - 1) * num
Return result
End If
End Function
Sub Main()
'calling the factorial method
Console.WriteLine("Factorial of 6 is : {0}", factorial(6))
Console.WriteLine("Factorial of 7 is : {0}", factorial(7))
Console.WriteLine("Factorial of 8 is : {0}", factorial(8))
Console.ReadLine()
EndSub
EndModule
When the above code is compiled and executed, it produces the following result −
Factorial of 6 is: 720
Factorial of 7 is: 5040
Factorial of 8 is: 40320

Param Arrays

At times, while declaring a function or sub procedure, you are not sure of the number of
arguments passed as a parameter. VB.Net param arrays (or parameter arrays) come into
help at these times.
The following example demonstrates this −

Module myparamfunc
FunctionAddElements(ParamArray arr AsInteger())AsInteger
Dim sum AsInteger=0
Dim i AsInteger=0

ForEach i In arr
sum += i
Next i
Return sum
EndFunction
SubMain()
Dim sum AsInteger
sum =AddElements(512,720,250,567,889)
Console.WriteLine("The sum is: {0}", sum)
Console.ReadLine()
EndSub
EndModule
When the above code is compiled and executed, it produces the following result −
The sum is: 2938

Passing Arrays as Function Arguments

You can pass an array as a function argument in VB.Net. The following example
demonstrates this −

Module arrayParameter
Function getAverage(ByVal arr AsInteger(),ByVal size AsInteger)AsDouble
'local variables
Dim i As Integer
Dim avg As Double
Dim sum As Integer = 0

For i = 0 To size - 1
sum += arr(i)
Next i
avg = sum / size
Return avg
End Function
Sub Main()
' an int array with5 elements '
Dim balance As Integer() = {1000, 2, 3, 17, 50}
Dim avg As Double
'pass pointer to the array as an argument
avg = getAverage(balance,5)
' output the returned value '
Console.WriteLine("Average value is: {0} ", avg)
Console.ReadLine()
EndSub
EndModule
When the above code is compiled and executed, it produces the following result −
Average value is: 214.4

Sub-procedure

Sub procedures are procedures that do not return any value. We have been using the Sub
procedure Main in all our examples. We have been writing console applications so far in
these tutorials. When these applications start, the control goes to the Main Sub procedure,
and it in turn, runs any other statements constituting the body of the program.
Defining Sub Procedures

The Sub statement is used to declare the name, parameter and the body of a sub
procedure. The syntax for the Sub statement is −
[Modifiers] Sub SubName [(ParameterList)]
[Statements]
End Sub
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.
 SubName − indicates the name of the Sub
 ParameterList − specifies the list of the parameters

Example

The following example demonstrates a Sub procedure CalculatePay that takes two


parameters hours and wages and displays the total pay of an employee −

Module mysub
SubCalculatePay(ByRef hours AsDouble,ByRef wage AsDecimal)
'local variable declaration
Dim pay As Double
pay = hours * wage
Console.WriteLine("Total Pay: {0:C}", pay)
End Sub
Sub Main()
'calling the CalculatePaySubProcedure
CalculatePay(25,10)
CalculatePay(40,20)
CalculatePay(30,27.5)
Console.ReadLine()
EndSub
EndModule
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

Passing Parameters by Value

This is the default mechanism for passing parameters to a method. In this mechanism, when
a method is called, a new storage location is created for each value parameter. The values
of the actual parameters are copied into them. So, the changes made to the parameter
inside the method have no effect on the argument.
In VB.Net, you declare the reference parameters using the ByVal keyword. The following
example demonstrates the concept −
Module paramByval
Sub swap(ByVal x AsInteger,ByVal y AsInteger)
Dim temp AsInteger
temp = x ' save the value of x
x = y ' put y into x
y = temp 'put temp into y
End Sub
Sub Main()
'local variable definition
Dim a AsInteger=100
Dim b AsInteger=200
Console.WriteLine("Before swap, value of a : {0}", a)
Console.WriteLine("Before swap, value of b : {0}", b)
' calling a function to swap the values '
swap(a, b)
Console.WriteLine("After swap, value of a : {0}", a)
Console.WriteLine("After swap, value of b : {0}", b)
Console.ReadLine()
EndSub
EndModule
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.

Passing Parameters by Reference

A reference parameter is a reference to a memory location of a variable. When you pass


parameters by reference, unlike value parameters, a new storage location is not created for
these parameters. The reference parameters represent the same memory location as the
actual parameters that are supplied to the method.
In VB.Net, you declare the reference parameters using the ByRef keyword. The following
example demonstrates this −

Module paramByref
Sub swap(ByRef x AsInteger,ByRef y AsInteger)
Dim temp AsInteger
temp = x ' save the value of x
x = y ' put y into x
y = temp 'put temp into y
End Sub
Sub Main()
'local variable definition
Dim a AsInteger=100
Dim b AsInteger=200
Console.WriteLine("Before swap, value of a : {0}", a)
Console.WriteLine("Before swap, value of b : {0}", b)
' calling a function to swap the values '
swap(a, b)
Console.WriteLine("After swap, value of a : {0}", a)
Console.WriteLine("After swap, value of b : {0}", b)
Console.ReadLine()
EndSub
EndModule
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 : 200
After swap, value of b : 100

Q 7. How can Message box be used in VB.Net? Give suitable example.

Ans. The show method of MessageBox is used to display User Specific message in a Dialog
Box and waits for the user to click a button. It returns an integer value indicating which
button is click by user. MessageBox is shown in the figure below:

MessageBox.Show (Text As String, Caption As String, Buttons As


System.Windows.Forms.MeesageBoxButtons, Icon As System.Windows.Forms.MessageBoxIcon)
As System.Windows.Forms.DialogResult
Here,

1. Text is a compulsory argument. The String that you specify as a Text will display as
a message in the Dialog Box.
33. Caption is a compulsory argument. The String that you specified as a caption will be
display in the title bar of the Dialog Box.
34. Buttons is used to specify type of buttons to display in the message box.
35. Icon is used to specify type of icon to display in the message box.

Example of MessageBox Function in VB.NET

Design a simple application that displays a message box when user clicks on Close Form
Button. If user clicks yes then form will be closed otherwise it remains open.
Step 1: Design a form as shown below:
Step 2: Now set properties of various controls as given below:

Control Name Property Name Value


Form1 Text MsgBox Function  Demo
Button1 Name cmdClose
Text Close Form
Step 3: Now Double click on Close Form Button and write following code display
Message Box.

If MessageBox.Show("Close Form?", "Confirmation", MessageBoxButtons.YesNo,


MessageBoxIcon.Question) = Windows.Forms.DialogResult.Yes Then
Me.Close()
End If

Q 8. Define InputBox function in VB.Net.

InputBox function display a prompt in the form of dialog box as shown below and waits for
the user to input some value in textbox or click a button.

If user clicks on OK button then it will return content of textbox in the form of string. If user
clicks on Cancel Button then it will return a blank value.
InputBox (Prompt As String,[Title As String=""], [DefaultResponse As String=""], [XPos As Integer
= -1], [YPos As integer = -1] ) As String
Here,
1. Prompt is a compulsory argument. The String that you specify as a Prompt will
display as a message in the InputBox Dialog.
36. Title is an optional Argument. The String that you specify as a Title will display in the
title bar of the InputBox. If you skip this argument then name of the application will
display in the title bar.
37. DefaultResponse is an Optional Argument. The String that you specify as a
DefaultResponse will display as a default value in the textbox of the InputBox. If you
skip this argument then Textbox of the InputBox is displayed empty.
38. XPos is an Optional Argument. It Specify the distance (in pixel) of the left edge of
the Input box from the left edge of the screen.
39. YPos is an Optional Argument. It Specify the distance (in pixel) of the upper edge of
the Input box from the top edge of the screen.

Example of InputBox Function in VB.NET

Design a simple application that ask user to enter name and display it in label using Input
Box Function.
Step 1: Design a form as shown below:

Step 2: Now set properties of various controls as given below:

Control Name Property Name Value


Form1 Text Input Box Function  Demo
Button1 Name cmdName
Text Click To Enter Name
Label1 Text Your Name Is:
Label2 Name lblName
Text Name
Step 3: Now Double click on Click To Enter Name Button and write following code
display Input Box and enter name.

lblName.Text = InputBox ("Enter Your Name", "Name", "", 100, 100)

Q 9. What is an Exception?

Ans.An exception is a problem that arises during the execution of a program. An exception
is a response to an exceptional circumstance that arises while a program is running, such as
an attempt to divide by zero.
Exceptions provide a way to transfer control from one part of a program to another. VB.Net
exception handling is built upon four keywords - Try, Catch, Finally and Throw.
 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

Q 10. Write down the various exception classes in .Net framework.

Ans. Exception Classes in .Net Framework-

In the .Net Framework, exceptions are represented by classes. The exception classes in
.Net Framework are mainly directly or indirectly derived from the System.Exception class.
Some of the exception classes derived from the System.Exception class are
the System.ApplicationException and System.SystemException classes.
The System.ApplicationException class supports exceptions generated by application programs. So
the exceptions defined by the programmers should derive from this class.
The System.SystemException class is the base class for all predefined system exception.
The following table provides some of the predefined exception classes derived from the
Sytem.SystemException class −

Exception Class Description


System.IO.IOException Handles I/O errors.

System.IndexOutOfRangeException Handles errors generated when a method refers to an


array index out of range.

System.ArrayTypeMismatchExceptio Handles errors generated when type is mismatched with


n the array type.

System.NullReferenceException Handles errors generated from deferencing a null object.

System.DivideByZeroException Handles errors generated from dividing a dividend with


zero.

System.InvalidCastException Handles errors generated during typecasting.

System.OutOfMemoryException Handles errors generated from insufficient free memory.

System.StackOverflowException Handles errors generated from stack overflow.

Q 11. How can exception handling problem be solved in VB.Net?

Ans. 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 error-handling statements.
These error handling blocks are implemented using the Try, Catch and Finally keywords.
Following is an example of throwing an exception when dividing by zero condition occurs −

Module exceptionProg
Sub division(ByVal num1 AsInteger,ByVal num2 AsInteger)
Dim result AsInteger
Try
result = num1 \ num2
Catch e AsDivideByZeroException
Console.WriteLine("Exception caught: {0}", e)
Finally
Console.WriteLine("Result: {0}", result)
EndTry
EndSub
SubMain()
division(25,0)
Console.ReadKey()
EndSub
EndModule
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
Q 12. How to create User defined exceptions in VB.Net?

Ans.Creating User-Defined Exceptions-You can also define your own exception. User-
defined exception classes are derived from the ApplicationException class. The following
example demonstrates this −

Module exceptionProg
PublicClassTempIsZeroException:InheritsApplicationException
PublicSubNew(ByVal message AsString)
MyBase.New(message)
EndSub
EndClass
PublicClassTemperature
Dim temperature AsInteger=0
Sub showTemp()
If(temperature =0)Then
Throw(NewTempIsZeroException("Zero Temperature found"))
Else
Console.WriteLine("Temperature: {0}", temperature)
EndIf
EndSub
EndClass
SubMain()
Dim temp AsTemperature=NewTemperature()
Try
temp.showTemp()
Catch e AsTempIsZeroException
Console.WriteLine("TempIsZeroException: {0}", e.Message)
EndTry
Console.ReadKey()
EndSub
EndModule
When the above code is compiled and executed, it produces the following result −
TempIsZeroException: Zero Temperature found

Throwing Objects

You can throw an object if it is either directly or indirectly derived from the System.Exception
class.
You can use a throw statement in the catch block to throw the present object as −
Throw [ expression ]
The following program demonstrates this −
Module exceptionProg
SubMain()
Try
ThrowNewApplicationException("A custom exception _ is being thrown here...")
Catch e AsException
Console.WriteLine(e.Message)
Finally
Console.WriteLine("Now inside the Finally Block")
EndTry
Console.ReadKey()
EndSub
EndModule
When the above code is compiled and executed, it produces the following result −
A custom exception is being thrown here...
Now inside the Finally Block
Unit IV
GUI Programming

Q 1. What do you understand by OOPs? Or Write down the various features of


OOPS.

Ans. Two types of program paradigm are used in Programming. These procedures are
Oriented and Object oriented programming. All new-time programming languages use
Object oriented programming. OOPs are a software development paradigm used to solve
problems encountered in a process oriented approach. Object oriented programming does
not allow data to flow into the system during program development. This prevents it from
sudden change by any other function. In this, the problem is solved by object, and in this
data and function work with object. Only the object's function can access the object's data.
Thus, it can be said that object oriented programming is a programming approach in which
data and functions are tied together called classes and used by objects. Where its data and
functions are different store and process for each object. Here, memory space is allocated
for the object in which its data and functions store.
Features of Object Oriented Programming

 Object  Inheritance

 Class  Polymorphism

 Data abstraction and  Dynamic Binding


encapsulation
 Message Passing

  Object: It is the basic run-time entity of OOPs. Which represents an object (person,
place, a bank account etc.). object is the variable of the class that executes the class
and processes the data using the methods available in it. Once the object is created,
it takes up space like other variables in memory.

 Class: Class is a user defined data type that contains data and code that is used by
the object. A class is a structure that defines the object's working. Many objects can
be created after creating a class. Thus it can be said that class is a collection of
objects of the same type.

 Data Abstraction and Encapsulation: Binding data and functions together is called
Encapsulation. This is the most important feature of the class. In this, the data cannot
be accessed outside the class, only the functions of the class can access it. The data
abstraction is from inputting and outputing the data without background process
details in which it is performed by the functions of the class.
 Inheritance: This is an important feature of OOPs that provides the facility of one
class to access the features of another class. In this, the object of one class can
access and use the properties of the other class as well. It implements the feature of
reuseability where to add new features to a class by creating a new class and
implementing the features of the old class in it as well as adding codes to the new
class.

 Polymorphism: It is also an important concept of OOPs that gives facility to create


and use more than one form. It is performed by both function and operators where
the function name or operator remains the same, but when the number of arguments
or types or types of operands are different, they are used differently and perform the
task. For example, the + operator is used to add numerical addition and strings.

 Dynamic Binding: In OOPs inheritance and polymorphism implement this feature,


which perform when the Binding or linking procedure is called. This is called dynamic
binding.

 Message Passing: Objects in OOPs communicate. Communicate by sending and


receiving objects information. In OOPs, the message passing function is performed
during a call. In which the information is input into the object through a function in the
form of a function argument and the method of the object gives it the process to
generate the result.

Q 2. What do you understand by an Inheritance in VB.Net?

Ans. Inheritance-Inheritance is an important feature of VB.Net that allows one class to use
another class feature. It allows to create a new class based on the already created class.
This supports reusability where they do not have to be recreated to add a feature or use the
features of the old class, inheritance from the old class and add them to the new class. The
class to be inherited is called base-class or parent class and the inherited class is derived or
child class.
Inheriting a class
To inherit the base class in the derived class, use the Inherits keyword and define the name
of the base class. After inheriting all the properties, methods, events, fields and constants of
the base class can be used in the derived class.
Inheritance Modifiers
Visual basic .Net provides some class level modifiers for inheritance.

 NotInheritable: The class cannot be inherited using it.

 MustInherit: On using it, it becomes mandatory to use the class in the base class. It
can only be used as a base class.

Overriding Properties and Methods in Derived Class


By default, derived class inherits all properties and methods of base class. Sometimes the
property or method inherited in the Derived class needs to be used differently, this is called
overriding. For this, VB.Net provides some modifiers for properties and methods used in
both Base class and Derived class which can be used to control overriding of any method
etc. Which are the following.
Properties and methods of Base Class

 Overridable: The property or method can be overridden by its use.

 NotOverridable: Property or method cannot be override when using it.

 MustOverride: It becomes mandatory to override the property or method when using


it.

 Properties and methods of derived class


Overrides: This is used when overriding an overridable property or method.
Limitations of Inheritance
All classes can be inherited in VB.NET. But all such classes in which NotInheritable keyword
is used cannot be inherited.

 Classes can also be inherited from other projects.

 VB.Net only supports Single and Multilevel inheritance.

 Inheritance to access type of both Base and Derived class must be equal only if
inheritance is possible.

Q 3. What are Access Specifiers in VB.NET?

Ans. All members of a class can directly access any other member. But we have to use
different types of Access Modifiers Provided by VB.NET to decide which Members of
another Class can access and how they can access. Members are declared in the following
way in a class created using object oriented programming in VB.NET -
Public
When a class is defined with a public Access Modifier, the members with publicAccess of
that class are equally Directly Accessible in the same Assembly and External Assembly.
Therefore, this type of class can be inherited in any assembly without any restriction.
Private
When a class is defined with a private Access Modifier, members with privateAccess of that
class are neither directly accessible in the Derived Class of the same Assembly nor in the
Derived Class of External Assembly. That is, such members are not directly accessible in
any derived class, but are always accessible through some public method.
Friend
This gives Friendly access to the variable, which means that if a Variable is Declared Friend
then that Variable can be used in the same class or used in the same Assembly.
Protected
When a class is defined with a protected Access Modifier, the members with protected
access to that class are Directly Accessible in the same Assembly and Derived Classes in
the External Assembly, but for Members outside the Derived Class, these Members are
Private Members' Behave in a manner.

Q 4. What is Overloading in VB.Net

Ans. Overloading- Overloading is an important feature of object oriented programming that


provides the facility to create multiple versions of a procedure and use them for different
tasks. In overloading, the name of the procedure is the same, there is only a difference in the
parameters, which helps the same procedure to perform different tasks with the same name.
Its purpose is to make different versions of a procedure, whose names remain the same.
Overloading rules
The following points should be kept in mind while overloading.

 Same Name: The names of all overloaded procedures must be the same.

 Different Signature: All overloaded procedures should have at least one of the
following differences only if the procedures can be overloaded.

1. Number of Parameters
2. Order of Parameters
3. Data Types of Parameters
4. Number of Type Parameters
5. Return Type

Example:

Public Class Shape

Public Function Area(ByVal radius As Double) As Double

Return Math.PI * radius * radius

End Function

Public Function Area(ByVal length As Double, ByVal width As Double) As Double

Return length * width


End Function

Public Function Area(ByVal a As Integer, ByVal b As Integer, ByVal c As


Integer) As Double

Dim s As Integer

s = (a + b + c) / 2

Return (Math.Sqrt(s * (s – a) * (s – b) * (s – c)))

End Function

End Class

MyBase keyword in VB.NET

Q 5. Where can MyBase keyword be used?

Ans. In mybase keyword inheritance, the base class's overrided method is used to call.
When ever the overrided method of base class is required while inheritance, then you can
call using the mybase keyword.
Example: When calculating the area of the circle as well as when calculating the area of the
Cone, then the area of the circle class needs to be override. In this, mybase is used to call
the area method of base class (Circle).

Circle.vb

Public Class Circle

Private cradius As Double

Public Property Radius() As Double

Get

radius = cradius

End Get

Set(ByVal value As Double)

If value < 0 Then

msgbox(“Wrong Input:”)
Else

cradius = value

End If

End Set

End Property

Public Overridable Function Area() As Double

Return Math.PI * Radius ^ 2

End Function

End Class

Cone.vb

Public Class Cone

Inherits Circle

Dim l As Double

Public Property length() As Double

Get

length = l

End Get

Set(ByVal value As Double)

l = value

End Set

End Property

Public Overrides Function Area() As Double

Return ((Math.PI * Radius * length) + MyBase.Area())


End Function

End Class

Limitations of MyBase keyword

 Mybase keyword can only be used for immediate base class.

 Mybase is not a real object, so assign value to variable by it, pass in procedure etc.
can not do.

 Can not use Mybase for MustOverride base class.

 Mybase cannot be used inside the base class.

 Mybase cannot be used for friend member.

Q 6. How to use MyClass Keyword in VB.Net?

Ans. MyClass Keyword- This keyword, like mybase, is used to call the overrided method of
the derived class when overriding a method. This makes sure that the called method is the
overrided method of this derived class.

Public Overrides Function Area () As Double

Return ((Math.PI * Radius * MyClass.length) + MyBase.Area ())

End function

Limitations of MyClass keyword

 MyClass is not a real object, so assign value to variable by it, pass in procedure etc.
can not do.

 Myclass can only be used for members of the same class.

 Can not use Myclass in standard modules.

 Myclass cannot be used with methods that cannot be override the base class.

Q 7. Discuss the overview of OLE (Object Linking and Embedding) in VB.Net.

Ans. Overview of OLE (Object Linking and Embedding)OLE is a technology that


provides the facility to link objects from one application to another application. Any
application program can be linked to its program using it. It links the Program Object,
implementing the feature of Object Oriented Programming. To use it, place the OLE Control
on the form from the Toolbox, as soon as you place it on the form, there is a Dialog Box
Display in which OLE Objects can be selected.

An application or any pre-made file can be used for OLE Object. For this this Dialogbox
contains Create New and Create From File Options. To link to a new application, select the
Create New option and select the object. And clicking OK button creates an Icon or Select
Object on the form. The features of that application can be accessed in your program by
double clicking on it.
Example: Selecting Excel Sheet

Double clicking on a sheet


Also, any pre-made file can also be linked by it, for this, select create from file and after
selecting the file and clicking on Ok button, it gets linked to the file application.

Example:

Q 8. What is windows form? How can we work with Form?

Ans. Windows form- It is a graphical application programming interface i.e. it is a GUI


component used for GUI in windows. All windows that are displayed in Windows are called
windows form in the programming. form is a control used to provide windows interface in
.Net. This control acts as a container for other windows controls. In this, by placing all the
controls of windows, User Interface is prepared for windows applications. The window that is
displayed when running the programs of Visual Basic is called form in design time.
The user does not have to work hard to create the form. It provides built in functionality. The
form designer window is used to design the form. Which is the main component of the visual
studio IDE.
Load form
To load a form, we use a load statement. To load a form, use the following Syntax.
Syntax: Load Form Name
Example: Load Application form
Unload Form
Use the unload statement to unload the form. Syntax to unload a form is as follows-
Syntax: Unload Form name
Example: Unload Application form
Form name is the name of the form to be loaded or unloaded, while the Show method loads
and displays a form, the Load statement does not represent the form. Once a form is loaded,
it takes all the necessary resources. So, to free them, we should unload the form after it is
over.
Show form
The Show Method is used to display a form. If the form is loaded, but remains hidden, the
show method brings it to the top of each window. If the form is not loaded, then the Show
method first loads it and then shows the use. The syntax of the show method is as follows -
Syntax: FormName.Show Mode
Example: ApplicationForm.Show Mode
Here Form Name is the name of the form and determines whether the form is model or
modelless. However, this argument is an option. Mode has the following values -
0 - Modeless (Default)
1- (Model)
Modelless forms are common forms. They communicate with the user, and can help the user
adopt any other format of the application.
A model form controls the application, not allowing the application to continue until the form
is closed. Therefore, a model form should have a close button or something similar, so that it
can be closed.
If the Show method can load or display the form, then why do we need the Load method?
The reasons for this are -
(i) Some forms do not need to be displayed. They only need to be loaded. These forms may
also contain procedures required for other applications or may also have specific functions,
such as doing something in the background.
For example a form with timer control that tracks time or other events that do not require a
user interface to view.
(ii) Can accelerate the performance of your form by loading the time forward / first. It takes
time to load the form, especially if the form has large bitmaps or many controls. By doing
this, the forms will move into memory but the show method can display them immediately.
Hide form
If our application uses too many forms, then other forms need to be hidden in order to create
space on the desktop. To hide the form, we will use the Hide method of the form, whose
syntax is as follows:
Syntax: From.Hide
We will use this statement to hide the form within its own code -
Syntax: Me.Hide
Hidden Forms are not unloaded, they are located in memory and can be displayed
immediately using the Show method. Forms that may need to be opened frequently should
be hidden at the time of not being used.
Startup Form
A particular application may have more than one form. When starting an application, the
main form is first loaded. We can control the form to be loaded initially by setting the start up
object in the project window. To open this dialog box, we will select the project menu and
click on the project properties. Then in the Startup Object List box, the form you want to start
first; Select it and click it after finishing it.
Controlling One form within another
(Controlling another form through one form)
Several forms are commonly used within an application. Therefore, controlling one form from
another is a very important task. For this, VB.NET has provided Show () and Hide ()
methods, through which we can easily control one form by another.
To understand this, open a new project, and install the button on the displayed form, and
add another form to the project and also place the button on it and coding in the code
module window and run the project. We do. Which gives the following output.
Unit V
Database Programming with ADO.net

Q 1. Describe the ADO.NET Architecture.

Data processing has traditionally relied primarily on a connection-based, two-tier model. As


data processing increasingly uses multi-tier architectures, programmers are switching to a
disconnected approach to provide better scalability for their applications.

ADO.NET Components

The two main components of ADO.NET for accessing and manipulating data are the .NET
Framework data providers and the DataSet.

.NET Framework Data Providers

The .NET Framework Data Providers are components that have been explicitly designed for
data manipulation and fast, forward-only, read-only access to data. The Connection object
provides connectivity to a data source. The Command object enables access to database
commands to return data, modify data, run stored procedures, and send or retrieve
parameter information. The DataReader provides a high-performance stream of data from
the data source. Finally, the DataAdapter provides the bridge between the DataSet object
and the data source. The DataAdapter uses Command objects to execute SQL commands
at the data source to both load the DataSet with data and reconcile changes that were
made to the data in the DataSet back to the data source.

The DataSet

The ADO.NET DataSet is explicitly


designed for data access
independent of any data source.
As a result, it can be used with
multiple and differing data sources,
used with XML data, or used to
manage data local to the
application.The DataSetcontains a
collection of one or
moreDataTableobjects consisting
of rows and columns of data, and
also primary key, foreign key,
constraint, and relation information
about the data in the
DataTableobjects.
The diagram illustrates the relationship between a .NET Framework data provider and
aDataSet.

Choosing a DataReader or a DataSet

When you decide whether your application should use aDataReader or aDataSet, consider
the type of functionality that your application requires. Use aDataSetto do the following:

 Cache data locally in your application so that you can manipulate it. If you only need
to read the results of a query, the DataReaderis the better choice.

 Remote data between tiers or from an XML Web service.

 Interact with data dynamically such as binding to a Windows Forms control or


combining and relating data from multiple sources.

 Perform extensive processing on data without requiring an open connection to the


data source, which frees the connection to be used by other clients.

If you do not require the functionality provided by the DataSet, you can improve the
performance of your application by using the DataReader to return your data in a forward-
only, read-only manner. Although the DataAdapter uses the DataReader to fill the
contents of a DataSet, by using the DataReader, you can boost performance because you
will save memory that would be consumed by the DataSet, and avoid the processing that is
required to create and fill the contents of the DataSet.

LINQ to DataSet

LINQ to DataSet provides query capabilities and compile-time type checking over data
cached in a DataSet object. It allows you to write queries in one of the .NET Framework
development language, such as C# or Visual Basic.

LINQ to SQL

LINQ to SQL supports queries against an object model that is mapped to the data structures
of a relational database without using an intermediate conceptual model. Each table is
represented by a separate class, tightly coupling the object model to the relational database
schema. LINQ to SQL translates language-integrated queries in the object model into
Transact-SQL and sends them to the database for execution. When the database returns
the results, LINQ to SQL translates the results back into objects.

ADO.NET Entity Framework

The ADO.NET Entity Framework is designed to enable developers to create data access
applications by programming against a conceptual application model instead of
programming directly against a relational storage schema. The goal is to decrease the
amount of code and maintenance required for data-oriented applications.

WCF Data Services

WCF Data Services is used to deploy data services on the Web or an intranet. The data is
structured as entities and relationships according to the specifications of the Entity Data
Model. Data deployed on this model is addressable by standard HTTP protocol.

Q 2. Describe the ADO.Net Object Model.

Ans. ADO.Net object model is nothing but the structured process flow through various
components. The object model can be pictorially described as −

The data residing in a data store or database is retrieved through the data provider. Various
components of the data provider retrieve data for the application and update data.
An application accesses data either through a dataset or a data reader.

 Datasets store data in a disconnected cache and the application retrieves data from
it.

 Data readers provide data to the application in a read-only and forward-only mode.

Data Provider

A data provider is used for connecting to a database, executing commands and retrieving
data, storing it in a dataset, reading the retrieved data and updating the database.
The data provider in ADO.Net consists of the following four objects −

Sr.No Objects & Description


.

1 Connection
This component is used to set up a connection with a data source.

2
Command
A command is a SQL statement or a stored procedure used to retrieve, insert, delete or modify data
in a data source.

3
DataReader
Data reader is used to retrieve data from a data source in a read-only and forward-only mode.

4
DataAdapter
This is integral to the working of ADO.Net since data is transferred to and from a database through a
data adapter. It retrieves data from a database into a dataset and updates the database. When
changes are made to the dataset, the changes in the database are actually done by the data
adapter.

There are following different types of data providers included in ADO.Net

 The .Net Framework data provider for SQL Server - provides access to Microsoft
SQL Server.

 The .Net Framework data provider for OLE DB - provides access to data sources
exposed by using OLE DB.

 The .Net Framework data provider for ODBC - provides access to data sources
exposed by ODBC.

 The .Net Framework data provider for Oracle - provides access to Oracle data
source.

 The EntityClient provider - enables accessing data through Entity Data Model (EDM)
applications.

DataSet

DataSet is an in-memory representation of data. It is a disconnected, cached set of records


that are retrieved from a database. When a connection is established with the database, the
data adapter creates a dataset and stores data in it. After the data is retrieved and stored in
a dataset, the connection with the database is closed. This is called the 'disconnected
architecture'. The dataset works as a virtual database containing tables, rows, and columns.
The following diagram shows the dataset object model −
The DataSet class is present in the System.Data namespace. The following table describes
all the components of DataSet −

Sr.No. Components & Description


DataTableCollection
1
It contains all the tables retrieved from the data source.
DataRelationCollection
2
It contains relationships and the links between tables in a data set.
ExtendedProperties
3
It contains additional information, like the SQL statement for retrieving data, time of retrieval, etc.
DataTable
4
It represents a table in the DataTableCollection of a dataset. It consists of the DataRow and DataColumn
objects. The DataTable objects are case-sensitive.
DataRelation
5
It represents a relationship in the DataRelationshipCollection of the dataset. It is used to relate two
DataTable objects to each other through the DataColumn objects.
DataRowCollection
6
It contains all the rows in a DataTable.
DataView
7
It represents a fixed customized view of a DataTable for sorting, filtering, searching, editing and
navigation.
PrimaryKey
8
It represents the column that uniquely identifies a row in a DataTable.
DataRow
9
It represents a row in the DataTable. The DataRow object and its properties and methods are used to
retrieve, evaluate, insert, delete, and update values in the DataTable. The NewRow method is used to
create a new row and the Add method adds a row to the table.
DataColumnCollection
10
It represents all the columns in a DataTable.
DataColumn
11
It consists of the number of columns that comprise a DataTable.

Connecting to a Database

The .Net Framework provides two types of Connection classes −

 SqlConnection − designed for connecting to Microsoft SQL Server.

 OleDbConnection − designed for connecting to a wide range of databases, like


Microsoft Access and Oracle.

Example 1
We have a table stored in Microsoft SQL Server, named Customers, in a database named
testDB. Please consult 'SQL Server' tutorial for creating databases and database tables in
SQL Server.
Let us connect to this database. Take the following steps −

 Select TOOLS → Connect to Database

 Select a server name and the database name in the Add


Connection dialog box.

 Click on the Test Connection button to check if the


connection succeeded.

 Add a DataGridView on the form.

 Click on the Choose Data Source combo box.

 Click on the Add Project Data Source link.

 This opens the Data Source Configuration Wizard.

 Select Database as the data source type

 Choose DataSet as the database model.

 Choose the connection already set up.

 Save the connection string.

 Choose the database object, Customers table in our example, and click the Finish
button.
 Select the Preview Data link to see the data in
the Results grid −

 When the application is run


using Start button available at the
Microsoft Visual Studio tool bar, it will
show the following window −

Example 2

In this example, let us access data in a DataGridView control using code. Take the following
steps −

 Add a DataGridView control and a button in the form.

 Change the text of the button control to 'Fill'.

 Double click the button control to add the required code for the Click event of the
button, as shown below −

ImportsSystem.Data.SqlClient
PublicClassForm1
PrivateSubForm1_Load(sender AsObject, e AsEventArgs) _
HandlesMyBase.Load
'TODO: This line of code loads data into the
'TestDBDataSet.CUSTOMERS' table.
You can move, or remove it, as needed.

Me.CUSTOMERSTableAdapter.Fill(Me.TestDBDataSet.CUSTOMERS)
'Set the caption bar text of the form.
Me.Text="tutorialspoint.com"
EndSub

PrivateSubButton1_Click(sender AsObject, e
AsEventArgs)HandlesButton1.Click
Dim connection AsSqlConnection=New sqlconnection()
connection.ConnectionString="Data Source=KABIR-DESKTOP; _
Initial Catalog=testDB;Integrated Security=True"
connection.Open()
Dim adp AsSqlDataAdapter=NewSqlDataAdapter _
("select * from Customers", connection)
Dim ds AsDataSet=NewDataSet()
adp.Fill(ds)
DataGridView1.DataSource= ds.Tables(0)
EndSub
EndClass

 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 −

 Clicking the Fill button displays the table


on the data grid view control −

Creating Table, Columns and Rows

We have discussed that the DataSet components


like DataTable, DataColumn and
DataRow allow us to create
tables, columns and rows,
respectively.
The following example
demonstrates the concept −

Example 3

So far, we have used tables and


databases already existing in our
computer. In this example, we will
create a table, add columns, rows
and data into it and display the table using a DataGridView object.
Take the following steps −

 Add a DataGridView control and a button in the form.

 Change the text of the button control to 'Fill'.

 Add the following code in the code editor.

PublicClassForm1
PrivateSubForm1_Load(sender AsObject, e
AsEventArgs)HandlesMyBase.Load
' Set the caption bar text of the form.
Me.Text = "tutorialspont.com"
End Sub
Private Function CreateDataSet() As DataSet
'creating a DataSetobjectfor tables
Dim dataset AsDataSet=NewDataSet()
' creating the student table
Dim Students As DataTable = CreateStudentTable()
dataset.Tables.Add(Students)
Return dataset
End Function
Private Function CreateStudentTable() As DataTable
Dim Students As DataTable
Students = New DataTable("Student")
' adding columns
AddNewColumn(Students,"System.Int32","StudentID")
AddNewColumn(Students,"System.String","StudentName")
AddNewColumn(Students,"System.String","StudentCity")
' adding rows
AddNewRow(Students, 1, "Zara Ali", "Kolkata")
AddNewRow(Students, 2, "Shreya Sharma", "Delhi")
AddNewRow(Students, 3, "Rini Mukherjee", "Hyderabad")
AddNewRow(Students, 4, "Sunil Dubey", "Bikaner")
AddNewRow(Students, 5, "Rajat Mishra", "Patna")
Return Students
End Function
Private Sub AddNewColumn(ByRef table As DataTable, _
ByVal columnType As String, ByVal columnName As String)
Dim column As DataColumn = _
table.Columns.Add(columnName, Type.GetType(columnType))
End Sub

'adding data into the table


PrivateSubAddNewRow(ByRef table AsDataTable,ByRef id AsInteger,_
ByRef name AsString,ByRef city AsString)
Dim newrow AsDataRow= table.NewRow()
newrow("StudentID")= id
newrow("StudentName")= name
newrow("StudentCity")= city
table.Rows.Add(newrow)
EndSub
PrivateSubButton1_Click(sender AsObject, e
AsEventArgs)HandlesButton1.Click
Dim ds AsNewDataSet
ds =CreateDataSet()
DataGridView1.DataSource= ds.Tables("Student")
EndSub
EndClass

 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 −

 Clicking the Fill button displays the table on the data grid view control −

Q 3. How to access Data Using Server Explorer?

Ans. Accessing Data Using Server Explorer- Server Explorer is


an important window of the Visual Studio IDE that helps in
making database connections. Before using the database, it
needs to connect to its program. This can be easily done with
the help of server explorer. This helps in making connections
with different types of databases. To display it, select Server
Explorer in the View menu or it can also be displayed by
pressing Ctrl + Alt + S key.
The toolbar of Server Explorer has four
buttons Refresh, delete, connect to
database and connect to server display.
To make a connection through Server
Explorer, select or add connection by
clicking or right clicking on connect to
database button. When doing this, the
Add connection Dialog box or
sometimes Choose Data Source
Window display starts.
The Add Connection Dialog box
depends on the Data Source
selected in the Choose Data
Source Dialog box. In fig, the
Connection Dialog box is displayed

like this after selecting Microsoft


SQL Server Database file.
According to the selected data source, after selecting the database file, click on the Test
connection button. When the connection is OK, click on the OK button. On clicking OK, all
files, tables, views, relations etc. of the selected database in Server Explorer Displayed.
From where they can be used on dataset or any other way.

Q 4. Discuss about SQLDB in VB.Net.

Ans. It is a Dababase server software developed by Microsoft that supports RDBMS. It


provides data accessing using SQL language. All Microsoft's programming language can be
used for the database by supporting it. It is an important part of ADO.Net. ADO.Net data
provider provides all the data accessing facilities separately for this. To use it, first SQLClient
imports the namespace for which the Import System.Data.SqlClient statement is used. It
consists of the following classes. The SQLConnection object is used for SQLDB.
Connection: The SQLConnection class is used in SQLDB. It is used to access data from
SQL Server. For this, in design mode, we use the Sqlconnection tool item which is available
in the data category in the toolbox. It can be used by placing it on the form. To use it by
coding, first let's create an object of SQLConnection class and define Connection String in it.
After this, the connection can be opened and used. In this, the following type of connection
string can be used.
Data Source=myServerAddress;Initial Catalog=myDataBase;User
Id=myUsername;Password=myPassword;
Server=myServerAddress;Database=myDataBase;User
ID=myUsername;Password=myPassword;Trusted_Connection=True;
Imports System.Data.SqlClient
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
Button1.Click
Dim constring As String = “Data Source=.\SQLEXPRESS;AttachDbFilename=C:\SQL Server 2000
Sample Databases\NORTHWND.MDF;Integrated Security=True;Connect Timeout=30;User
Instance=True”
Dim con As SqlConnection = New SqlConnection(constring)
Try
con.Open()
MsgBox(“Connected Sucessfully”)
con.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
End Class
Command: Object of SQLCommand class is used for SQL connection. To use it, we declare
its object and define all its important properties and call the methods.
Imports System.Data.SqlClient
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
Button1.Click
Dim constring As String = “Data Source=.\SQLEXPRESS;AttachDbFilename=C:\SQL Server 2000
Sample Databases\NORTHWND.MDF;Integrated Security=True;Connect Timeout=30;User
Instance=True”
Dim con As SqlConnection = New SqlConnection(constring)
Dim cmd As SqlCommand = New SqlCommand
cmd.Connection = con
cmd.CommandText = “Select * from Products”
Try
con.Open()
Dim dr As SqlDataReader = cmd.ExecuteReader
dr.Read()
MsgBox(dr.Item(0))
con.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
End Class
DataAdapter and DataSet: It contains the DataAdapter object of SQLDataadpter and
dataset normal dataset.
Dim con_str As String = “Data Source=.\SQLEXPRESS;AttachDbFilename=C:\SQL Server 2000
Sample Databases\NORTHWND.MDF;Integrated Security=True;Connect Timeout=30;User
Instance=True”
Dim con As New SqlConnection(con_str)
Dim ada As SqlDataAdapter
Dim ds As New DataSet
Try
con.Open()
ada = New SqlDataAdapter(“Select * from Products”, con)
ada.Fill(ds)
con.Close()
Dim i As Integer
For i = 0 To ds.Tables(0).Rows.Count – 1
MsgBox(ds.Tables(0).Rows(i).Item(1))
Next
Catch ex As Exception
MsgBox(ex.Message)
End Try

Q 5. How to display Data on data bound controls.

Ans. In VB.NET, we can get data from Database through Data Bound Controls and display
the data in these controls on the form. Here the following steps are followed to display the
data through Text Box (Data Bound Controls) -
Step 1: Create a new project in VB.NET and design a new form. Connected to the database
with the help of oledb Data Adapter and create Dataset.
Step 2: From the Tool Box, design three Text Boxes and one button on the form.
Step 3: By selecting the Text Box, in the Properties window of the text box, we set the Data
Bindings and Dataset properties. The same steps are done for the remaining Text Boxes.
Step 4: Under the Form do the following Coding –

Dim dm As Binding Manager Base


Private Sub Form Load (By Val sender As System. Object, By Val a As System. EventArgs)
Handles My Base.Load
dm = Me. Binding context (Dataset 11, “Pubs”)
Oledb Data Adaptor 1. File (Dataset 11)
bm.position = 1
End Sub
Step 5: Double click on Button and do the following Coding in the Code Window –

Me.Binding Context (Dataset 11, “Pubs”).Position


=(Me.Binding Context (Dataset 11, “Pubs” ).Position + 1)
End Sub
Step 6: Let us run the form.

Q 6. How to Display data on data grid?

Ans. Data Receiving in Data Grid: Here we are creating an example where the data can be
accessed to help the programmer. For this, follow the following steps -
• Start a new Windows application project and name it "Exam".
• Drag the OleDb Data Adapter Control from the toolbox and drop it onto the form, then the
wizard of the data adapter starts.
• After the wizard is finished, the controls are inserted into the tray.
• Dataset is required to get the data.
• Once DataSat is created, the Data Grid control from the toolbox is created on the form from
the toolbox.
• Selects the data source property of this control, then the list comes under it.
• Selects Data Set 11. Groups option from this list.
In order to get the data from the adapter, in the load event of the form, coding as follows-

Private Sub Form1 Load (By Val Sender As System. Object, By Val e As System. Event
Args)
Handles My Base. Load

OleDb Data Adapter1.Fill (Data Set11)

End Sub

Data Grid appears when coming back to the form.


• When the project is run, we get its output.
• In this example, the database is received inside the Data Grid. In the same way, the
programmer can also get the data under different control as per his requirement.
Such as - DataGrid, ComboBox, ListBox, TextBox, etc.

You might also like